How to dynamically name variables in a matlab struct?

51 views (last 30 days)
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 Comment
Stephen23
Stephen23 on 31 Jan 2019
Edited: Stephen23 on 31 Jan 2019
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:

Sign in to comment.

Accepted Answer

Luna
Luna on 30 Jan 2019
You are almost there.
Define your algor2 and probl2 as cell arrays with braces:
algor2 = {'alg1','alg2','alg3'}
probl2 = {'prob1','prob2','prob3','prob4'}

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!