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

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

Réponse acceptée

Hernia Baby
Hernia Baby le 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 commentaire
takeru misawa
takeru misawa le 13 Sep 2021
教えていただきありがとう御座います。他の回答者様のご意見も考慮してご回答いただきありがとう御座います。

Connectez-vous pour commenter.

Plus de réponses (1)

Toru Ikegami
Toru Ikegami le 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 commentaire
takeru misawa
takeru misawa le 13 Sep 2021
教えていただきありがとう御座います。cell配列は様々な場面で役立ちますね。

Connectez-vous pour commenter.

Catégories

En savoir plus sur 構造体 dans Help Center et File Exchange

Produits


Version

R2019b

Community Treasure Hunt

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

Start Hunting!