Matlab Arrayfun with manual class

Let's say I have an array of 1x2 objects of class handle with the SetProperty method. Can I use arrayfun to call the SetProperty method for each class along with a vector to use it to set the property value?

+3
source share
2 answers

Yes, you can:

arrayfun(@(x,y)x.SetProperty(y), yourHandleObjects, theValues)
+1
source

You can also create a class so that the call is SetPropertyvectorized:

 class Foo < handle
      methods(Access=public)
            function SetProperty(this,val)
                 assert(numel(this)==numel(val));
                 for i=1:numel(this)
                      this(i).prop = val(i);
                 end
            end
      end
end

Then you can create a vector and immediately call the method:

    f = repmat(Foo(),[1 2]);
    f.SetProperty( [5 3]);
+3
source

All Articles