I have two structures with same field. One structure is called alum; the other is called piezo. I am assigning from these two structures doing the following:
for n=1:N
if n==1; Q0{n}=alum.Q; theta{n}=alum.th; end
if n==2; Q0{n}=piezo.Q; theta{n}=piezo.th; end
end
======================= Question: can I do this by defining a label
lbl={'alum' 'piezo'}
and then using the label in a loop to access structure alum when n=1 and structure piezo when n=2?
Thank you.

2 件のコメント

James Tursa
James Tursa 2018 年 10 月 1 日
Why is there a loop? Could N be larger than 2?
Stephen23
Stephen23 2018 年 10 月 2 日
編集済み: Stephen23 2018 年 10 月 2 日
"can I do this by defining a label... then using the label in a loop to access structure..."
It is certainly possible to do that, if you want to force yourself into writing slow, complex, buggy code that is hard to debug. Read this to know why:
You could either use an if or switch to select them, or put the data into one array and use highly efficient indexing, or use a non-scalar array, or a table, or ...

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

 採用された回答

Jan
Jan 2018 年 10 月 2 日
編集済み: Jan 2018 年 10 月 2 日

0 投票

Instead of defining labels, you can store the variables in an array:
data = {alum, piezo}; % E.g. a cell array
for n=1:N
Q0{n} = data{n}.Q;
theta{n} = data{n}.th;
end
A struct array might be smart also. Then do not store the meaning of the variable in the name, but as an extra field:
data(1).Q = rand;
data(1).th = rand;
data(1).type = 'alum';
data(1).Q = rand;
data(1).th = rand;
data(1).type = 'piezo';
Then you can create Q0 easily without a loop:
Q0 = {data.Q};
The general idea is it, not to store the actual data (here the meaning of the variable) in the names of the variables, but as data.

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File Exchange で MATLAB Support Package for Raspberry Pi Hardware についてさらに検索

製品

リリース

R2017b

質問済み:

2018 年 10 月 1 日

編集済み:

2018 年 10 月 2 日

Community Treasure Hunt

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

Start Hunting!

Translated by