在我的Matlab代码中,我有一个“质量”的对象数组,它是一个类的对象,用来描述质量、速度、速度等。
为了加快仿真速度,我想通过使用更多的向量操作来减少循环的使用。其中一项操作是获取当前质量与所有其他质量的距离。
我想这样解决这个问题:
%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循环的情况下对其进行优化?
我希望我的问题足够清楚,否则我会优化它;)
发布于 2016-01-31 21:12:05
我用这段代码来重现你的问题。对于未来的问题,请尝试在你的问题中包括这样的例子:
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]-3https://stackoverflow.com/questions/35118376
复制相似问题