構造体配列の要素の参照方法について

44 views (last 30 days)
takeru misawa
takeru misawa on 8 Sep 2021
Commented: takeru misawa on 13 Sep 2021
初歩的な質問で大変恐縮なのですが、
s.a = 1
s.b = [1,2]
s.c = 'test'
のような構造体配列sがある時、要素を指定する際にs.aと文字を使って指定するのではなく、s(1)がs.a, s(2)がs.bを指定しているのと同義になるような、数値を用いて指定することはできないでしょうか。

Accepted Answer

Hernia Baby
Hernia Baby on 8 Sep 2021
2案ほどあります
1つ目は@Toru Ikegamiさんのようにcell型に変換すること
2つ目はa, b, cを格納してインデックスから呼び出す方法です
ここでは2つ目を紹介します
--------------------------------------------------------------------------------------
まずは準備
s.a = 1;
s.b = [1,2];
s.c = 'test';
ここで名前を取り出します
name = fieldnames(s)
name = 3×1 cell array
{'a'} {'b'} {'c'}
それぞれ表示させます
for i = 1:length(name)
disp( name{i} )
disp( s.(name{i}) )
end
a
1
b
1 2
c
test
構造体はフィールド変数参照型なので1番目や2番目といった概念より、辞書的なイメージです
ここら辺の議論はHow to access a field of a struct by indexing?もご参考にしてください
  1 Comment
takeru misawa
takeru misawa on 13 Sep 2021
教えていただきありがとう御座います。他の回答者様のご意見も考慮してご回答いただきありがとう御座います。

Sign in to comment.

More Answers (1)

Toru Ikegami
Toru Ikegami on 8 Sep 2021
こんにちは.
関数 struct2cell を使うのがいちばん手っ取り早いかと思います.
s.a = 1;
s.b = [1,2];
s.c = 'test';
c = struct2cell(s);
c{1}
ans = 1
c{2}
ans = 1×2
1 2
c{3}
ans = 'test'
  1 Comment
takeru misawa
takeru misawa on 13 Sep 2021
教えていただきありがとう御座います。cell配列は様々な場面で役立ちますね。

Sign in to comment.

Categories

Find more on 構造体 in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!