Cannot obtain structure elements where both field and variable are indexed into

2 ビュー (過去 30 日間)
z8080
z8080 2021 年 8 月 29 日
編集済み: z8080 2021 年 8 月 30 日
Say I have a structure of students' information, where the indexing of both the name field and the structure itself are of interest:
>> students(1).name='john'
students =
1×2 struct array with fields:
name
>> students(2).name='andrea'
students =
1×2 struct array with fields:
name
Say I want to obtain the initial of several students' names. One student at a time, this works fine:
>> students(1).name(1)
ans =
'j'
>> students(2).name(1)
ans =
'a'
Also fine is if I call up the entire field:
>> students(1:2).name
ans =
1×1 cell array
{'john'}
ans =
1×1 cell array
{'andrea'}
But when I index into the structure AND the field name, this produces the notorious error:
>> students(1:2).name(1)
Expected one output from a curly brace or dot indexing expression, but there were 2 results.
Various forum threads suggest the structure or its field need to be encapsulated in square brackets, but this still did not work. If I do this with cell arrays, it also does not help.
I've hit this problems numerous times and always get around it with for loops, but in my current script I'd have to do this many times, and it'd be very helpful to know what the right syntax is for obtaining this sort of nested indexing, if there is one.
  4 件のコメント
Stephen23
Stephen23 2021 年 8 月 30 日
編集済み: Stephen23 2021 年 8 月 30 日
"Various forum threads suggest the structure or its field need to be encapsulated in square brackets,"
Which ones? Please give link/s so that I can make corrections to those threads.
It is not possible to index into both the structure and the field simultaneously (except in the trivial case that the structure indexing returns a scalar structure), so any thread claiming that brackets or curly braces are "needed" is not correct.
z8080
z8080 2021 年 8 月 30 日
編集済み: z8080 2021 年 8 月 30 日
I tried to look for those threads I saw but could not find them/it. I could well have misinterpreted that they were suggesting it is possible to index into both the structure and the field simultaneously. I now understand this to require a for loop, or to employ arrayfun, as Turlough Hughes suggested

サインインしてコメントする。

採用された回答

Turlough Hughes
Turlough Hughes 2021 年 8 月 29 日
Try the following:
students(1).name='john';
students(2).name='andrea';
arrayfun(@(x) students(x).name(1), 1:2).'
ans = 2×1 char array
'j' 'a'

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by