Loop in structure or cell array
이전 댓글 표시
Hi, I have many matrices (about 2000) in my workspace. The names of these matrices include many underscore (e.g. Trace_1_1_30_1_1). I know it is a bad idea to dynamically changes the matrices name, but is there any way to use loop for each number after underscore. for example something like:
for i=1:m
for j=1:n
for k=1:s
for g=1:r
for ee=1:p
A=Trace_i_j_k_g_ee
end
.
.
end
답변 (2개)
Jan
2017년 10월 11일
You have 2000 matrices in your workspace?! This is a bad idea. Names like "Trace_1_1_30_1_1" hide important information in the name of a variable, where it is hard, complicated, slow, ugly, tedious and prone to bugs to access them. See https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval .
No, there is no clean method to create these loops or indexing inside the names. You are aware already, that the dynamic fields names are a serious problem. Then get rid of them: Clean up your workspace once and create a nice and efficient data structure. Perhaps:
C = cell(m, n, s)
for i1 = 1:m
for i2 = 1:n
for i3 = 1:s
C{i1, i2, i3} = eval(sprintf('Trace_%d_%d_%d', i1, i2, i3));
end
end
end
But do not use this to access the matrices. Do not include it in your current code. It is slow and bad and evil. Use this only to clean up the workspace. A multi-dimensional array might be an option also.
Afterwards indexing in the array gets efficient and trivial. Good luck!
댓글 수: 2
Babak V-Ghaffari
2017년 10월 11일
편집: Babak V-Ghaffari
2017년 10월 11일
"Imported"? By
load(FileName)
? Then it would be much better to catch the output:
Data = load(FileName);
Then processing the filednames(Data) is easier, faster and secure.
Babak V-Ghaffari
2017년 10월 11일
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!