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

Antworten (2)

Jan
Jan am 11 Okt. 2017

1 Stimme

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 Kommentare

Babak V-Ghaffari
Babak V-Ghaffari am 11 Okt. 2017
Bearbeitet: Babak V-Ghaffari am 11 Okt. 2017
Hi Jan, Thanks you. Actually, I have not created these matrices. These matrices were created by a software from an experimental work. I only imported the dat file and I am trying to change the matrix names to make them easier to work with.
Jan
Jan am 11 Okt. 2017
Bearbeitet: Jan am 11 Okt. 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.

Melden Sie sich an, um zu kommentieren.

Babak V-Ghaffari
Babak V-Ghaffari am 11 Okt. 2017

0 Stimmen

One more question, I get error because there is no Trace_1_1_1_1. Is there any way to check for example if Trace_1_1_1_1 is exist in workspace put it in C but if it is not exist ignore it and go to the Trace_1_1_1_2. I tried to use "if exist()" but I am not sure how to use this in cell array. for example maybe it is somthing like:
C = cell(m, n, s)
for i1 = 1:m
for i2 = 1:n
for i3 = 1:s
if exist(eval(sprintf('Trace_%d_%d_%d', i1, i2, i3)))==1;
C{i1, i2, i3} = eval(sprintf('Trace_%d_%d_%d', i1, i2, i3));
end
end
end
end

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 11 Okt. 2017

Bearbeitet:

Jan
am 11 Okt. 2017

Community Treasure Hunt

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

Start Hunting!

Translated by