Creating an array of structs and using the field directly?

2 Ansichten (letzte 30 Tage)
Jan Kappen
Jan Kappen am 19 Nov. 2015
Kommentiert: Guillaume am 26 Feb. 2016
Hey guys. I'm wondering if there is a workaround for doing something like this:
a = {[struct('field',1) struct('field',2)].field}
which works in octave but not in matlab ("invalid syntax at '.'. Possibly a ')', ']' or '}' is missing"), I have to use a temporary variable. This is quite annoying. Is there a workaround?
Thanks!
  1 Kommentar
Guillaume
Guillaume am 26 Feb. 2016
Note that this has nothing to do with with the fact that you're creating an array of structure. You're effectively doing
a = fn(someargs).field %where fn can be any function
which is illegal in matlab. Functions cannot be indexed using {} or . indexing.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Andy Campbell
Andy Campbell am 26 Feb. 2016
Bearbeitet: Andy Campbell am 26 Feb. 2016
Do you need it to be a one liner? If not:
s = [struct('field',1) struct('field',2)];
a = {s.field};
Otherwise you can use arrayfun, but this isnt the most readable.
>> arrayfun(@(s) getfield(s,'field'), [struct('field',1) struct('field',2)])
ans =
1 2
>> arrayfun(@(s) getfield(s,'field'), ...
[struct('field',1) struct('field',2)], ...
'UniformOutput',false)
ans =
[1] [2]

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by