How to dynamically name variables in a matlab struct?

26 次查看(过去 30 天)
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'}

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by