Matlab OOP accessing properties from an object array
arrays, matlab, matrix, oop
Solution
Simple but unintuitive
y=[x.Value]
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`.
EDIT:
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]);
Then
>> [x.Value]
ans =
3 4 5 6 20 10
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]
Problem
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; ``` This however fails and only puts the value of x(3) into y..... and: ``` y(:) = x(:).Value; ``` Throws an error. 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.