3

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.

1 Answer 1

5

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]
Sign up to request clarification or add additional context in comments.

3 Comments

Aka x holds arrays but they have unequal lengths.
See my edits for details. x holds an array of sample classes. The joys of non strict type!
Thanks man that fixed it I was storing my arrays in vertical format and not horizontal and it didn't matter when I was indexing them but it does when combing them so I switched them and its working now.... whoops.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.