How to change the name of variables using a loop?

조회 수: 315 (최근 30일)
Kathleen
Kathleen 2014년 9월 25일
편집: Stephen23 2014년 10월 10일
I need to do the same matrix calculations repeatedly, but I want to rename the variable within the loop. e.g. I need matrices R_1 R_2 R_3 R_4. I want to be able to set matrix R_1=( calcs for ii=1); R_2=( calcs for ii=2), etc. I know I can convert ii to a string using num2str(ii), but how do I concatenate that to R? R_ii=(calcs for ii)?
Am I going to need some sort of cell array to do that? I'm trying to avoid cells.
  댓글 수: 3
José-Luis
José-Luis 2014년 9월 25일
편집: José-Luis 2014년 9월 25일
Are all those variables the same size? If so then just store them in an array:
for ii = 1:n
your_mat(:,ii) = something;
end
Stephen23
Stephen23 2014년 9월 25일
편집: Stephen23 2014년 10월 10일
José-Luis: good point. This should include array preallocation though:
for ii = n:-1:1
your_mat(:,ii) = something;
end

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

채택된 답변

Stephen23
Stephen23 2014년 9월 25일
편집: Stephen23 2014년 9월 25일
In MATLAB it is (almost always) better to not create variable names on the fly:
Use a cell or struct instead.
I know you were looking for a tidy solution... this is the tidy solution.

추가 답변 (2개)

Iain
Iain 2014년 9월 25일
Cells ARE the way to go.
Structures would be preferable to what you want
mystruct.description = 'blah blah';
mystruct = setfield(mystruct,['R_' num2str(ii) ], values);
However, sometimes, in rare cases, not using a monolithic storage solution is the only practical option. This option should be avoided whenever possible.
eval(['R_' num2str(ii) ' = values;']);

Titus Edelhofer
Titus Edelhofer 2014년 9월 25일
Hi Kathleen,
why do you want to avoid cells? They are a perfect fit - and much cleaner/safer/easier to use than any clumsy and error prone variable creation based on names and indices ...?
Titus

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by