1

In my Matlab code I have an object-array of 'masses' which are an object of a class which describes the mass, speed, accerleration etc.

To speed up the simulation I want to reduce the usage of for-loops with using more vector operations. One of the operations is to get the distance of the current mass to all others.

I would like to solve it like that:

%position is a vector with x and y values e.g. [1 2]
%repeat the current mass as many times as there are other masses to compare with
currentMassPosition = repmat(obj(currentMass).position, length(obj), 2);      
distanceCurrentMassToOthersArray = obj(:).position - currentMassPosition;

I cannot use the colon-indexing operation on the object array. Currently i use a for-loop where I iterate through every single object. Do you have any tips to optimise that without using a for loop?

I hope my question was clear enough, otherwise I will optimise it ;).

Diluvian
  • 25
  • 4
  • I recommend avoiding objects in Matlab, if you can do the same with other means. If you still want to have an object that "groups" mutliple variables together, consider making an object of arrays instead of arrays of objects, such that you can call `obj.position(:)` for vectorized operations. – flawr Jan 31 '16 at 19:46
  • Thank you for the tip. It's due to my challenge that I wanted to learn coding in a object-oriented way. I'm sure that I'm not doing it perfectly. – Diluvian Jan 31 '16 at 20:54
  • To precise the comment of flawr, [unless you use Matlab 2015b or newer, you should avoid OOP in performance critical parts of your code](http://stackoverflow.com/questions/1693429/is-matlab-oop-slow-or-am-i-doing-something-wrong) – Daniel Jan 31 '16 at 21:02

1 Answers1

3

I used this code to reproduce your problem. For future questions please try to include such examples into your question:

classdef A
    properties
        position
    end
    methods
        function obj=A()
            obj.position=1;
        end
    end
end

.

%example code to reproduce
x(1)=A
x(2)=A
x(3)=A
%line which causes the problem
x(:).position-3

To understand why this is not working, take a look at the output of x(:).position, just type it into the console. You get multiple ans values, indicating a comma separated list of multiple values. If you use [x(:).position] instead, you get an array of doubles. The correct code is:

[x(:).position]-3
Daniel
  • 36,610
  • 3
  • 36
  • 69