2

I have an array of objects (of user-defined class), and I want to call a method for all of them. The method represents a processing step for several data channels, tied with treir own objects.

I see two solutions:

1) Writing a for-loop to call method for every object in a vector:

for i=1:numel(objArray)
    objArray(i).step;
end

2) Adding length check inside class method, like this:

function step(obj) 
    if numel(obj)>1
        for i=1:numel(obj)
            step(obj(i));
        end
        return;
    end
    % some processing ...
end

But I don't like both solutions, because I should add the same code for every method call in a first case or for every method definition in a second case. Is there a better way to do it?

2
  • Can you clarify your question? Commented May 31, 2017 at 10:14
  • What is not clear in it? I have 1xN vector of objects and I want to call methods simply by objArray.step instead of for-loops. Commented May 31, 2017 at 10:23

1 Answer 1

2

The typical pattern to follow would be something like:

function step(objArray)
    for i = 1:numel(objArray)
        % some processing on objArray(i)
    end
end

No need for that weird if in your question that recursively calls the method on a single element - just do the processing directly on each element.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, it is much simpler! I think I should write public methods with this pattern, which vectorize other private methods for a single object. Though in the case of get methods this will not work that simple for objects properties.
You're right that a get method is always called on the first element of an array of objects. But you can always use values = [objArray.value]: this will call the get method for each element of the object array, get the property value, and collect them into an array.
Yes, also I think to maintain the original dimension of object vector and add out = reshape(out, size(objArray));

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.