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
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
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 Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!