Naming matrices in a for loop

조회 수: 16 (최근 30일)
Zena Assaad
Zena Assaad 2015년 10월 20일
댓글: Zena Assaad 2015년 10월 26일
Hi all,
I have a for loop that runs from 1 to 6. Within that for loop I am creating 2 matrices:
for F = 1:6
A = zeros(3,20);
B = zeros(3,20);
end
I have just used zeros(3,20) for example purposes. The actual matrices are not zero matrices. The matrices are dependant on other variables which change with F. So when I run the for loop I get 6 A matrices and 6 B matrices. My question is, is there a way of changing the names of these matrices that doesn't involve a long code. I was hoping to change them to something as simple as A1, A2, A3... B1, B2, B3...
I am trying to avoid having a large code.
Thanks in advance!
  댓글 수: 1
Stephen23
Stephen23 2015년 10월 20일
편집: Stephen23 2015년 10월 20일
" as simple as A1, A2, A3... B1, B2, B3..." is a really really bad idea that will make your code slow, ugly and buggy: Do not create dynamic variable names! Read this to know why creating dynamic variable names is poor programming practice, even though many beginners seem to think that it is a great idea:

댓글을 달려면 로그인하십시오.

채택된 답변

the cyclist
the cyclist 2015년 10월 20일
편집: the cyclist 2015년 10월 20일
for F = 1:6
A{F} = zeros(3,20);
B{F} = zeros(3,20);
end
  댓글 수: 4
the cyclist
the cyclist 2015년 10월 20일
What Image Analyst says is certainly true. The best data type to store your data depends on a few considerations. For example, if all your matrices are a fixed size, then a numeric type makes sense. For example:
A = zeros(3,20,6);
for F = 1:6
A(:,:,F) = rand(3,20);
end
When you can't do something that simple, other data types are useful. Those of us have been using MATLAB for a long time will probably choose a data type based on some combination of (a) how appropriate it is for the task at hand, and (b) how familiar we are with it from past use. Image Analyst might choose an array of structures, where I might choose to use a table.
It's good to at least scan the examples in the documentation, to begin gaining a sense of what is possible. It can be confusing at first, though!
Zena Assaad
Zena Assaad 2015년 10월 26일
Thank you all for your comments. They have been very helpful!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Image Analyst
Image Analyst 2015년 10월 20일
See the FAQ http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F for why this is a bad idea. Just use a 2 or 3D array instead.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by