Loop in structure or cell array
Show older comments
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
Answers (2)
Jan
on 11 Oct 2017
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 Comments
Babak V-Ghaffari
on 11 Oct 2017
Edited: Babak V-Ghaffari
on 11 Oct 2017
"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
on 11 Oct 2017
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!