Naming cells in for loop

조회 수: 4 (최근 30일)
Sebastian Daneli
Sebastian Daneli 2021년 8월 27일
댓글: Stephen23 2021년 8월 27일
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
Stephen23
Stephen23 2021년 8월 27일
"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.

댓글을 달려면 로그인하십시오.

채택된 답변

Awais Saeed
Awais Saeed 2021년 8월 27일
편집: Awais Saeed 2021년 8월 27일
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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by