필터 지우기
필터 지우기

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 CenterFile Exchange에서 Structures에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by