Accessing Nth element of a given field for all elements in a non-scalar structure.
8 次查看(过去 30 天)
显示 更早的评论
I have a 1xM non-scalar structure with a field with N elements. For example (with M=3 and N=10):
for N=1:10;
s(1).x{N} = rand(100,1);
s(2).x{N} = 5.*rand(100,1);
s(3).x{N} = rand(100,1)./3;
end
and I want to create a new cell array out of the nth element of all M structure elements (sorry for the confusing phrasing, I'm not sure if there's a better way to refer to this?), for example:
a = {s(1).x{n} s(2).x{n} s(3).x{n}};
But I'd like to do this without referencing all M structure elements (1:3 in this example), because in reality there are a lot more than M=3.
So far I've tried:
a = s.x{n};
a = {s.x{n}};
a = deal(s(:).x{n});
and a few other variants, but everything just gives me an error of "Expected one output from a curly brace or dot indexing expression, but there were 2 results."
Is there a simple syntax for doing this, or do I really need to write out all M elements or use a for loop or something? Thanks!
0 个评论
回答(2 个)
Stephen23
2018-2-5
编辑:Stephen23
2018-2-5
for N=1:10;
s(1).x{N} = rand(100,1);
s(2).x{N} = 5.*rand(100,1);
s(3).x{N} = rand(100,1)./3; % fixed the incorrect parentheses.
end
n = 4;
getfield(s,{':'},'x',{n})
or if that does not work then you could use arrayfun:
n = 4;
arrayfun(@(S)S.x(n),s)
Note the choice of parentheses is significant!
2 个评论
Stephen23
2018-2-6
编辑:Stephen23
2018-2-6
@dandan: my answer does not use the uniformoutput option, all you need is this:
c = arrayfun(@(S)S.x(n),s)
This works because the field x is a cell array, therefore getting element n using () parentheses returns a scalar cell array: a scalar cell array is a uniform output, and so there is no need to set uniformoutput to false.
Walter Roberson
2018-2-5
arrayfun(@(S) S.x{n}, s)
2 个评论
Stephen23
2018-2-5
??? Error using ==> arrayfun
Non-scalar in Uniform output, at index 1, output 1.
Set 'UniformOutput' to false.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!