FAQ: How can I create variables A1, A2,...,A10 in a loop?
이전 댓글 표시
How can I create variables A1, A2,..., A10 in a loop?
댓글 수: 6
Huw S
2017년 4월 21일
Whilst the "don't do it" stuff is worthwhile. Whats the answer to this question? Because there is no way the other solutions help for some situations.
Stephen23
2017년 4월 21일
Here is another explanation of why dynamic variable names are bad way to write code, with links to many other answers and forums:
Before using dynamic variable names, try reading and understanding why it is a really bad idea, and read all of the links and references on all of the linked pages.
Jan
2019년 3월 15일
채택된 답변
추가 답변 (2개)
Robert Cumming
2014년 9월 10일
편집: Robert Cumming
2014년 9월 10일
I 100% agree with Jan that creating new variables on the fly is something that should be avoided - but if you must then please consider this alternative method:
function generateVariableOnFly
% lets tic/toc to compare the use of eval and assignin
tic
eval ( 'a = zeros(10,10);' )
toc
% an alternate method is to use a
% sub function which assigns vars in the caller function:
tic
variableCreator ( 'b', zeros(10,10) )
toc
% validate that a and b both exist and are the same:
isequal ( a, b )
end
% Use a sub function which assigns variable in the caller function:
function variableCreator ( newVar, variable )
assignin ( 'caller', newVar, variable );
end
To complete Jans example you could use this in the following way:
for ii=1:10
variableCreator ( sprintf ( 'A%i', ii ), ii )
end
That would create variables A1, A2.... A10.
댓글 수: 3
Oussama HAYANE
2020년 1월 1일
Thank you very much for this answer
for ii=1:10
variableCreator ( sprintf ( 'A%i', ii ), ii )
end
it gives axactly what I looked for
Now, my quaestion is :
What can I do if I want to use one of these variables on an other loop
i.e. : how can I call them using Index 'A%i'
I want to modify a value of one these vriables but i don't know wich one : in my code I have a condition that determine wich one of these 'A%i' will be modified; so how can I call this 'A%i' to give it a new value
example: A5 = 8;
and I want to change it to : A5 = 19;
@Oussama HAYANE: use indexing. Indexing is much simpler and more efficient than what you are trying to do:
A(5) = 8;
A(5) = 19;
Indexing is explained quite well in the introductory tutorials:
Is there a particular reason why you need to write such slow, complex, obfuscated code?
shahil kushwaha
2017년 6월 13일
0 개 추천
thanks a lot
카테고리
도움말 센터 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!