Marian Galik
Marian Galik

Reputation: 876

Calling method for every class instance in array (Matlab)

I'm new to Matlab and I was told, that it is faster to use dot operator instead of for loop when performing the same operation on array.

Example:

A = 1:200
A = A .* 10;

Instead of:

A = 1:200
for i = 1:200
    A(i) = A(i) * 10;
end

I have created an multi-dimensional array of Objects (the objects are instances of class I created). Is it possible to call the same method with the same arguments on all instances without using the for loop?

I have tried this 3 approaches, but they don't work (A is three-dimensional array):

A(:,:,:).methodName(argument1, argument2);
A.methodName(argument1, argument2);
A..methodName(argument1, argument2);

Upvotes: 4

Views: 3232

Answers (1)

Edric
Edric

Reputation: 25160

You should be able to call your method using the 'functional form'

methodName(A, argument1, argument2)

However, 'methodName' will need to handle the fact that you've passed an array of object. Here's a simple example

classdef Eg
    properties
        X
    end
    methods
        function obj = Eg( arg )
            if nargin == 0
                % Default-constructor required
                arg = [];
            end
            obj.X = arg;
        end
        function x = maxX( objs )
        % collect all 'X' values:
            xVals = [objs.X];
            % return the max
            x = max( xVals(:) );
        end
    end
    methods ( Static )
        function testCase()
        % Just a simple test case to show how this is intended to work.
            for ii = 10:-1:1
                myObjArray(ii) = Eg(ii);
            end
            disp( maxX( myObjArray ) );
        end
    end
end

If possible, it's better (in MATLAB) to have fewer objects storing larger arrays, rather than lots of small objects.

Upvotes: 4

Related Questions