Accessing Nth element of a given field for all elements in a non-scalar structure.
8 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (2)
Stephen23
am 5 Feb. 2018
Bearbeitet: Stephen23
am 5 Feb. 2018
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 Kommentare
Stephen23
am 6 Feb. 2018
Bearbeitet: Stephen23
am 6 Feb. 2018
@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
am 5 Feb. 2018
arrayfun(@(S) S.x{n}, s)
2 Kommentare
Stephen23
am 5 Feb. 2018
??? Error using ==> arrayfun
Non-scalar in Uniform output, at index 1, output 1.
Set 'UniformOutput' to false.
Siehe auch
Kategorien
Mehr zu Structures finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!