Creating an array of structs and using the field directly?

조회 수: 1 (최근 30일)
Jan Kappen
Jan Kappen 2015년 11월 19일
댓글: Jan 2015년 11월 23일
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!

채택된 답변

Stephen23
Stephen23 2015년 11월 19일
편집: Stephen23 2015년 11월 19일
It is not clear why you need to structure at all, as the output is simply a cell array with some numeric scalars in it (Octave code below)
>> {[struct('field',1) struct('field',2)].field}
ans =
{
[1,1] = 1
[1,2] = 2
}
>> {struct('field',{1,2}).field}
ans =
{
[1,1] = 1
[1,2] = 2
}
>> {1,2}
ans =
{
[1,1] = 1
[1,2] = 2
}
If the input is already a structure, then you can simply access the field values using the methods given in the documentation for non-scalar structures:
{X.field}
  댓글 수: 6
Jan Kappen
Jan Kappen 2015년 11월 20일
Sorry, you're right of course. But you explicitely mentioned the "proper usage of non-scalar arrays", so I thought there is a obvious mistake?
Stephen23
Stephen23 2015년 11월 20일
편집: Stephen23 2015년 11월 20일
Again it depends on what you mean by "mistake": perhaps you need to have two scalar structures, this I do not know. See my answer for one way of defining a non-scalar structure using a single call to struct.

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

추가 답변 (1개)

Jan
Jan 2015년 11월 19일
As long as you insist on using standard struct : No, there is no workaround. Using a temporary variable is not a big deal and does not waste additional resources.
You can create your own object class, which solves the problem. But this will be less efficient.
  댓글 수: 3
Jan Kappen
Jan Kappen 2015년 11월 20일
Can I accept both answers as correct answers, since they both are correct?
Jan
Jan 2015년 11월 23일
You can accept one answer only. But you can vote for more answers and a comment is useful also.

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

카테고리

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