Naming cells in for loop
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Sebastian Daneli
le 27 Août 2021
Commenté : Stephen23
le 27 Août 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 commentaire
Stephen23
le 27 Août 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.
Réponse acceptée
Awais Saeed
le 27 Août 2021
Modifié(e) : Awais Saeed
le 27 Août 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 commentaire
Stephen23
le 27 Août 2021
Indexing is simpler, neater, easier to debug, and much more efficient.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!