3

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 2

3

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]);
Sign up to request clarification or add additional context in comments.

2 Comments

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.
@AndrewAshworth what you are saying sounds interesting. Can you give an example? (For my own education purposes)
1

Yes, you can:

arrayfun(@(x,y)x.SetProperty(y), yourHandleObjects, theValues)

1 Comment

Thanks! This is straightforward, I have no idea why I was having so much trouble with the syntax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.