Naming cells in for loop

4 Ansichten (letzte 30 Tage)
Sebastian Daneli
Sebastian Daneli am 27 Aug. 2021
Kommentiert: Stephen23 am 27 Aug. 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 Kommentar
Stephen23
Stephen23 am 27 Aug. 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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Awais Saeed
Awais Saeed am 27 Aug. 2021
Bearbeitet: Awais Saeed am 27 Aug. 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

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by