フィルターのクリア

How to access the Nth element of 1x1 struct with 5 fields?

31 ビュー (過去 30 日間)
Hasan Kaan Tuna
Hasan Kaan Tuna 2023 年 7 月 28 日
コメント済み: Stephen23 2023 年 7 月 28 日
Hi,
I have a 1x1 struct with 5 fields defined in workspace. Also, in that struct there are two collumns as "field" and "value". How can I access the name of Nth element of that struct?
When I try,
struct(n)
Matlab gives me following error:
Index exceeds matrix dimensions.
Thank you for your help.
  2 件のコメント
Stephen23
Stephen23 2023 年 7 月 28 日
編集済み: Stephen23 2023 年 7 月 28 日
@Hasan Kaan Tuna: please upload your data in a MAT file by clicking the paperclip button.
"Also, in that struct there are two collumns as "field" and "value"."
You wrote that the structure is 1x1, so it cannot have "two collumns". Most likely you are getting mixed up by how the workspace / variable viewer displays structures, which by default shows the fields as columns (i.e. nothing to do with the structure size). Rather than rely on a contradictory explanation it would be much more reliable to have the original data to work with.
"When I try, struct(n) Matlab gives me following error"
Of course: if a structure only has one element, what do you expect to get when you try to access its non-existent 2nd element? The same applies for any other array type, not just structure arrays.
Dyuman Joshi
Dyuman Joshi 2023 年 7 月 28 日
Do you want to get the field names of the struct? Then use fieldnames.

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

採用された回答

Pranavkumar Mallela
Pranavkumar Mallela 2023 年 7 月 28 日
編集済み: Pranavkumar Mallela 2023 年 7 月 28 日
Hi Hasan,
I understand that you want to access the nth field in a struct. As Dyuman indicated, you can use the ''fieldnames" function.
Please find code for the same:
s = struct('field1', 1, 'field2', 2,'field3', 3,'field4', 4,'field5', 5); % your 5-field struct
s_fields = fieldnames(s); % use fieldnames
n=2;
nthfield = s_fields{n}; % accessing the nth field
val = s.(nthfield); % val holds the value of the nth field
For more information regarding the "fieldnames" function,you can refer to the following documentation: https://www.mathworks.com/help/matlab/ref/fieldnames.html
Hope this helps! Thanks!
  3 件のコメント
Hasan Kaan Tuna
Hasan Kaan Tuna 2023 年 7 月 28 日
Thank you. Who would have guess the curly braces :)
Stephen23
Stephen23 2023 年 7 月 28 日
"Who would have guess the curly braces :)"
No guessing is required with MATLAB: FIELDNAMES returns a cell array, as its documentation clearly states.
Also this data type is shown in the command window:
S = struct('x',1,'y',2);
C = fieldnames(S)
C = 2×1 cell array
{'x'} {'y'}

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

その他の回答 (0 件)

カテゴリ

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

タグ

製品


リリース

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by