Say I have a 1x2 object array of a handle class with a method SetProperty. Can I use arrayfun to call the SetProperty method for each class, along with a vector for it to use to set the property value?
2 Answers
You can also design the class so that the call to SetProperty will be vectorized:
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 call the method on it directly:
f = repmat(Foo(),[1 2]);
f.SetProperty( [5 3]);
2 Comments
krapht
I've used this before too. I'm more motivated to use arrayfun now, though, because I can control what gets passed to the function. This was an issue when I had a bunch of nested classes, and I never knew if self was going to refer to the class I wanted or its superclass, which depended on from where I called the method.
Andrey Rubshtein
@AndrewAshworth what you are saying sounds interesting. Can you give an example? (For my own education purposes)
Yes, you can:
arrayfun(@(x,y)x.SetProperty(y), yourHandleObjects, theValues)
1 Comment
krapht
Thanks! This is straightforward, I have no idea why I was having so much trouble with the syntax.