使用'colon'索引的对象数组上的向量运算 [MATLAB]



在我的 Matlab 代码中,我有一个"质量"的对象数组,它是描述质量、速度、加速度等的类的对象。

为了加快模拟速度,我想通过使用更多的矢量运算来减少 for 循环的使用。其中一个操作是获取当前质量到所有其他质量的距离。

我想这样解决它:

%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;

我不能对对象数组使用冒号索引操作。目前,我使用for循环,在其中循环访问每个对象。您是否有任何技巧可以在不使用 for 循环的情况下对其进行优化?

我希望我的问题足够清楚,否则我会;)优化它。

我用这段代码重现了你的问题。对于将来的问题,请尝试在您的问题中包含以下示例:

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

要了解为什么这不起作用,请查看 x(:).position 的输出,只需将其输入控制台即可。您将获得多个ans值,指示多个值的逗号分隔列表。如果改用[x(:).position],则会得到一个双精度数组。正确的代码是:

[x(:).position]-3

最新更新