Reputation: 1910
Let's say I create an array of structs in matlab using:
mystruct = repmat(struct('field1',1, 'field2', ones(10,1)), 10, 1 );
For my purposes (simple example aside), I would find it very useful to get a vector output from using:
myvector = mystruct(:).field2(1)
However this gives me the error:
'Scalar index required for this type of multi-level indexing.'
EDIT: What I expect to get is the first element of the ones vector, from each struct in the array, hence a 10x1 vector of '1'.
I could easily manually using a for loop go through each value in my struct and assign to myvector but that seems incredibly cumbersome and also slow. Any thoughts?
Upvotes: 1
Views: 1987
Reputation: 12214
I'm assuming you're trying to collect all of the field2
vectors into myvector
:
myvector = [mystruct(:).field2];
Returns:
myvector =
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
EDIT: Per your comment, you can use the above and throw out the data you don't want (myvector(2:end,:) = [];
in this case). This is a pretty memory intensive way to do it though. There may be a way to pull what you want using structfun
or similar but I'd need to think about how to do it.
EDIT2: Try arrayfun(@(x) x.field2(1), mystruct)
and see if this returns what you're looking for.
Upvotes: 1
Reputation: 81
In two step you can:
get your struct filed2 as a matrix:
foo = [mystruct.field2];
get the first row (that contains the first indices of the field2)
myvector = foo(1, :);
Upvotes: 1