Naming cells in for loop
4 次查看(过去 30 天)
显示 更早的评论
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
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
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
1 个评论
Stephen23
2021-8-27
Indexing is simpler, neater, easier to debug, and much more efficient.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!