フィルターのクリア

How to dynamically name variables in a matlab struct?

47 ビュー (過去 30 日間)
ELCIO S
ELCIO S 2019 年 1 月 30 日
編集済み: Stephen23 2019 年 1 月 31 日
Hi everyone.
I need to create a 'struct' to save some datas.
This datas refers to results of solve 28 problems using 10 differents algorithms each one being executed 100 times. To simplify, let suppose the I have 4 problems and 3 algorithms. I need to find a way to dynamically name all the variable of the struct. So I try to make a code like this:
for i=1:3
algor = {@alg1,@alg2,@alg3}
algor2 = ['alg1','alg2','alg3']
probl = {@prob1,@prob2,@prob3,@prob4}
probl2 = ['prob1','prob2','prob3','prob4']
for j=1:4
for k=1:100
[M,jM] = algor{i}(probl{j}); % I know that this line is okay!
dataM(k).(algor2{i}).(probl2{j}) = M(end).mem; % I think my problems are in "algor2{i}" and/or in "probl2{j}"
datajM(k).(algor2{i}).(probl2{j}) = jM(end).mem;
end
save('dataM.mat','dataM');
save('datajM.mat','datajM');
end
end
My doubt is:
1) there is a way to transform 'algor' in 'algor2' (and 'probl' in 'probl2') in a different way that I did?
2) about 'dataM(k).(algor2{i}).(probl2{j}) = M(end).mem' (and datajM(k).(algor2{i}).(probl2{j}) = jM(end).mem) I received the error mesage:
Brace indexing is not supported for variables of this type.
Error in main (line 40)
dataM(k).(algor2{i}).(probl2{j}) = M(end).mem;
So, what am I doing wrong? How to do it in the right way?
See that, what I am trying to do in 2) is dynamically name the variable in a struct. I need the variable name in the format "dataM.alg1.prob1".
Thank you for your help!
  1 件のコメント
Stephen23
Stephen23 2019 年 1 月 31 日
編集済み: Stephen23 2019 年 1 月 31 日
Note that those are field names, not variable names. The structure itself is a variable, and the structure has fields (which is what your question actually refers to). Structure field names can be generated or accessed dynamically:
Accessing variable names is not recommended:

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

採用された回答

Luna
Luna 2019 年 1 月 30 日
You are almost there.
Define your algor2 and probl2 as cell arrays with braces:
algor2 = {'alg1','alg2','alg3'}
probl2 = {'prob1','prob2','prob3','prob4'}
  2 件のコメント
ELCIO S
ELCIO S 2019 年 1 月 30 日
Thank you. It works!
Luna
Luna 2019 年 1 月 31 日
Your welcome :)

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

その他の回答 (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