How can I use cycle in structures?

4 ビュー (過去 30 日間)
Giorgi
Giorgi 2015 年 1 月 22 日
コメント済み: Giorgi 2015 年 1 月 22 日
Hi all, Well I have structure that contains multiple variables for example
% code
a.a=1;
a.b=2;
a.c=3;
a.d=4;
a.e=5;
a.f=6;
etc...
The problem is that I want to call the third variable of a structure without calling its name for example in such way a.(3) but it does not work, so my idea is to use for loot for it but I do not know how to use it. Any ideas would be a great job for me.

採用された回答

Guillaume
Guillaume 2015 年 1 月 22 日
If the fields of the structure have no meaning and only their order is important, then you shouldn't be using structures. If all you're storing in your fields are scalars, then a matrix would be better, otherwise a cell array. Using structure fields for that is just as bad as using dynamically generated variable names.
So, assuming you're not using the structure as a structure, I'd convert it to a cell array with struct2cell and then optionally to a matrix with cell2mat:
c = struct2cell(a);
%accessing the 3rd variable is then:
var3 = c{3};
%if all values are scalar, then:
m = cell2mat(c);
var3 = m(3);
Otherwise, the answer to your question is to use fieldnames and dynamic field names:
fn = fieldnames(a);
var3 = a.(fn{3});
  1 件のコメント
Giorgi
Giorgi 2015 年 1 月 22 日
Thank you for your response I used fieldnames and it works fine :)

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by