Creating an array of structs and using the field directly?

조회 수: 2 (최근 30일)
Jan Kappen
Jan Kappen 2015년 11월 19일
댓글: Guillaume 2016년 2월 26일
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
Guillaume
Guillaume 2016년 2월 26일
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.

댓글을 달려면 로그인하십시오.

답변 (1개)

Andy Campbell
Andy Campbell 2016년 2월 26일
편집: Andy Campbell 2016년 2월 26일
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]

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by