Matlab OOP从对象数组访问属性 [英] Matlab OOP accessing properties from an object array
问题描述
Matlab的新功能来自C/C ++……
New to Matlab come from C/C++......
我有一个对象数组,我正在尝试访问数组中每个对象的值,并将它们连接到一个变量中.
I have an array of objects and I'm trying to access the values of every single object in the array and concatenate them into one variable.
Class sample
properties(GetAccess = 'public', SetAccess ='public')
ID;
Value;
end
methods
function obj = sample(id, value)
obj.ID = id;
obj.Value = value;
end
end
end
然后我创建一个包含一些对象的矩阵.
Then I make an matrix containing some of the objects.
x = sample.empty(3,0);
x(1) = sample(1,3);
x(2) = sample(1,4);
x(3) = sample(1,5);
然后,我想从对象中获取所有值并将它们存储到新数组中.
Then I want to get all the values from the objects and store them into a new array.
y = x(:).Value;
但是这失败了,仅将x(3)的值放入y .....和:
This however fails and only puts the value of x(3) into y..... and:
y(:) = x(:).Value;
引发错误.
任何帮助将不胜感激.我知道我可以使用循环来做到这一点,但我正在尝试以最快,最有效的方式做到这一点.
Any help would be appreciated. I know I could do this with loops but I'm trying to do it in the fastest and most efficient way.
推荐答案
简单但不直观
y=[x.Value]
为什么? x.Value
不是内存的连续块,因此不能直接分配给数组.调用x.Value
依次从每个x
对象返回Value数据成员. Matlab将此视为单独的操作.通过将调用括在[]
中,您将告诉matlab通过串联每个结果来制定一个连续的数组.然后可以将其分配给双精度数组y
.
Why? Well x.Value
is not a contiguous block of memory, so cannot be directly assigned to an array. Calling x.Value
returns the Value data member from each x
object in turn. Matlab treats this as separate operations. By enclosing the call in []
you are telling matlab to formulate a contiguous array by concatenating each result. This can then be assigned to an array of doubles, y
.
关于您的评论,如果x在不同对象中的长度不同,则上述代码可以正常工作,即
Regarding your comment, the above code works fine if x is of different length in different objects i.e. . .
x(1) = sample(1,3);
x(2) = sample(1,[4 5 6]);
x(3) = sample(1,[20 10]);
然后
>> [x.Value]
ans =
3 4 5 6 20 10
如果您想让'y'是一个参差不齐的末端向量,例如C ++中的向量,则需要使用单元格数组表示法(大括号)
If you mean you want 'y' to be a ragged ended vector like is possible with a vector of vectors in C++, you need to use cell array notation (curly braces)
>> y = {x.Value}
y =
[3] [1x3 double] [1x2 double]
这篇关于Matlab OOP从对象数组访问属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!