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.
类别
在 帮助中心 和 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!