Naming cells in for loop
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Sebastian Daneli
el 27 de Ag. de 2021
Comentada: Stephen23
el 27 de Ag. de 2021
I can't figure this out, how to I name 10 cells in a for loop? A loop that looks something like this
for i=1:10
c(insert solution here)=cell(2,1);
end
Which should result in 10 cells c1, c2, ..., c10. They have to be named in a for loop since the actual problem that I'm trying to solve has do be solved with such a loop, and the results are to be stored in the cells.
1 comentario
Stephen23
el 27 de Ag. de 2021
"Which should result in 10 cells c1, c2, ..., c10."
Ugh. Do NOT do this. Unless you want to force yourself into writing slow, complex, inefficient, obfuscated code:
"They have to be named in a for loop since the actual problem that I'm trying to solve has do be solved with such a loop, and the results are to be stored in the cells."
That you need to use a loop and cell arrays certainly does NOT require magically naming variables.
The simple, neat, and very efficient MATLAB approach is to use indexing. You should use indexing too.
Respuesta aceptada
Awais Saeed
el 27 de Ag. de 2021
Editada: Awais Saeed
el 27 de Ag. de 2021
You want to create a cell array with 10 cells? If yes then use
for i=1:10
c{i} = cell(2,1);
end
If you meant you want to create 10 cell arrays with names like c1,c2,c3 all the way up to c10 then I know only about one solution that is by using eval. Note that using this method is NOT RECOMMENDED. It has been said many times in this forum and by MATLAB itself.
n = 10;
for i = 1:1:n
eval(['c', int2str(i),' = cell(2,1)'])
end
1 comentario
Stephen23
el 27 de Ag. de 2021
Indexing is simpler, neater, easier to debug, and much more efficient.
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements 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!