Remove for-loop by using cellfun
Mostrar comentarios más antiguos
var_name = {'A','B','C'};
for i=1:length(var_name)
eval([cell2mat(var_names(i)) '=zeros(10,1);'])
end
How can I do?
Thanks in advance
3 comentarios
Approaches involving dynamic variable naming are almost always flawed. I think that you/we should work upstream and change the approach so you don't have to use EVAL and dynamic names. What are you trying to achieve overall, and where/how are these A, B, and C variables defined?
Christophe
el 3 de Jul. de 2014
If all "variables" contents are 10x1 numeric arrays, it would be much more natural/efficient (and simpler) to build an array of zeros. For 3 "variables", for example:
nData = 3 ;
data = zeros( 10, nData ) ;
and then use e.g.
data(:,2) = ...
to get the column vector for the second data.
Respuesta aceptada
Más respuestas (3)
Robert Cumming
el 3 de Jul. de 2014
Create the dynamic variables inside a struct instead of using eval
var_name = {'A','B','C'};
for i=1:length(var_name)
myStruct.(var_name{i}) = zeros(10,1);
end
1 comentario
Christophe
el 3 de Jul. de 2014
the cyclist
el 3 de Jul. de 2014
0 votos
the cyclist
el 3 de Jul. de 2014
Editada: John D'Errico
el 3 de Jul. de 2014
Please tell us you are not naming those 106 variables A,B,C, ..., AA, AB, AC, etc!
Could you do this via a cell array instead?
for n = 1:106
A{n} = zeros(10,1);
end
and use those as your variables?
2 comentarios
Christophe
el 3 de Jul. de 2014
John D'Errico
el 3 de Jul. de 2014
Changed zeros{10,1} to zeros(10,1).
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!