This is an experimental question only! There is no need to answer it and please to not vote for it. This is neither my question nor my answer, but only an example for a nicer, more convenient, more usable FAQ, which is less stuffed with commercials.
FAQ: How can I create variables A1, A2,...,A10 in a loop?
676 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
How can I create variables A1, A2,..., A10 in a loop?
6 comentarios
Respuesta aceptada
Jan
el 26 de Dic. de 2012
Editada: Jan
el 24 de Abr. de 2017
1 comentario
Edward Byers
el 19 de Jul. de 2016
Hi Is there a good way to store multiple iterated LinearModel objects? i.e. with an index notation that makes it easy to loop and call specific instances, I have tried:
mdl{x} = fitlm(tbl,modelspec);
But that doesn't work, as: "Assignment using () is not allowed for a FitObject."
Más respuestas (2)
Robert Cumming
el 10 de Sept. de 2014
Editada: Robert Cumming
el 10 de Sept. de 2014
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 comentarios
Oussama HAYANE
el 1 de En. de 2020
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;
Stephen23
el 1 de En. de 2020
Editada: Stephen23
el 1 de En. de 2020
@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?
Ver también
Categorías
Más información sobre Function Creation en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!