0

I have an array of classes (we'll call it a, size Mx1) that contains a property (feature) which holds a 1xN array. I'm trying to get a new matrix that is MxN which contains rows of each of the feature property of the objects. For example:

M = 3
N = 4
a(1,1).feature = [1 2 3 4]
a(2,1).feature = [5 6 7 8]
a(3,1).feature = [9 10 11 12]

then, given some function, the answer would end up as:

ans = [1 2 3 4; 5 6 7 8; 9 10 11 12]

Currently, I've been using the following:

ans = cell2mat({a.feature}')

however I feel there should be a way to do this without having to convert to a cell, switch the dimensions, and then convert to a matrix. Am I correct or would this be the best way to solve the issue? I haven't been able to find any such function in the documentation.

1 Answer 1

1

When you have an array of objects and you access a property using dot referencing, a comma separated list is returned. This comma separated list can be passed to a function and will appear as multiple input arguments.

In your case, you can pass this comma separated list to cat and specify that you want each value to be concatenated to the next along the first dimension. So this would simply become:

features = cat(1, a.feature)

%// 1     2     3     4
%// 5     6     7     8
%// 9    10    11    12

This is functionally equivalent to:

features = cat(1, a(1).feature, a(2).feature, a(3).feature, ..., a(end).feature);
Sign up to request clarification or add additional context in comments.

Comments

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.