Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用';冒号';索引[MATLAB]_Matlab_Class_Object_Vector_Indexing - Fatal编程技术网

使用';冒号';索引[MATLAB]

使用';冒号';索引[MATLAB],matlab,class,object,vector,indexing,Matlab,Class,Object,Vector,Indexing,在我的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

在我的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

要理解为什么这不起作用,请查看
x(:).position的输出,只需在控制台中键入它即可。您会得到多个
ans
值,表示一个。如果改用
[x(:).position]
,则会得到一个双精度数组。正确的代码是:

[x(:).position]-3

我建议避免使用Matlab中的对象,如果您可以使用其他方法进行同样的操作。如果您仍然希望有一个对象“将多个变量分组在一起”,请考虑创建一个数组对象,而不是对象数组,这样您就可以调用代码> Obj.Posits(:):/VoC>进行矢量化操作。谢谢您的提示。正是由于我的挑战,我想以面向对象的方式学习编码。我肯定我做得不是很完美。准确地说,这是非常有帮助的!非常感谢你的努力。我明天就去试试。
[x(:).position]-3