Sairus
Sairus

Reputation: 394

Call method for object arrays in Matlab

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?

Upvotes: 2

Views: 1681

Answers (1)

Sam Roberts
Sam Roberts

Reputation: 24127

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.

Upvotes: 2

Related Questions