4

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);
3
  • 1
    No, you have to loop manually. There are functions arrayfun/cellfun which allow one-line syntax but they (obviously) are also loops under the hood and may be slower then a manual loop. Matrix multiplication and method invocation are two very different things. Commented Oct 30, 2011 at 18:05
  • Is it possible to use those functions (arrayfun/cellfun) also on array of objects? (since my array is small, the speed probably wouldn't be an issue and it would simplify the code readibility) Commented Oct 30, 2011 at 18:11
  • 1
    This should work: arrayfun( @(x) x.methodName(argument1, argument2), A ) Commented Oct 30, 2011 at 19:38

1 Answer 1

4

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.

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

2 Comments

+1 I like how you iterate backwards creating the array of objects (allocating space once and avoiding dynamically growing it)
You can also use logical indexing, for example. x=max([objs.X]>0).

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.