2

I have an array of objects, all of the same class. Is it possible to apply a function (defined in the methods section in the class) to all the objects in the array at once? for example, the class definition is:

classdef myClass
        properties
            x=0;
        end

        methods
            function obj=plus1(obj)
                obj.x=obj.x+1;
            end
        end

    end

Now I can create an object A of class myClass:

A=myClass;

and apply the method plus1:

A=A.plus1;

However, if I create an array of objects of the same class:

A(1,10)=myClass;

is it possible to apply 'plus1' to the 10 objects of A at once?

something like:

A(:)=A(:).plus1;

Thanks guys :)

2 Answers 2

1

You may use arrayfun

>> A = arrayfun( @(x) x.plus1, A );
Sign up to request clarification or add additional context in comments.

Comments

1

As long as the method plus1 is defined for arrays of objects, it will work:

    methods
        function obj=plus1(objList)
            for obj = objList(:)'
               obj.x=obj.x+1;
            end
        end
    end

Now you can call A = plus1(A) or A=A.plus1 even if A is an array of objects.

1 Comment

I'm not sure this quite works; I think some values may get mis-assigned. Noted in the chat: chat.stackoverflow.com/rooms/26329/…

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.