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
Jan 2017년 10월 11일

1 개 추천

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
Babak V-Ghaffari 2017년 10월 11일
편집: Babak V-Ghaffari 2017년 10월 11일
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 2017년 10월 11일
편집: Jan 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
Babak V-Ghaffari 2017년 10월 11일

0 개 추천

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

카테고리

도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2017년 10월 11일

편집:

Jan
2017년 10월 11일

Community Treasure Hunt

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

Start Hunting!

Translated by