Dynamically update cell without clearing previous content?
显示 更早的评论
Hi all,
I'd like to dynamically update cell content and size, without clearing the previous cell content. Check the following code:
clear; clc;
nr = 1;
for i = 1:5
a = cell(1, nr);
a{:, i} = {nr};
nr = nr + 1;
end
,
>> a
a =
[] [] [] [] {1x1 cell}
>> a{5}
ans =
[5]
Imagine I do not know how many iterations I will do, meaning cell size of 'a' needs to be dynamically updated with the number of iterations (which is why I use a = cell(1, nr) in the loop). However, after each iteration, content of 'a' is cleared, so I get only the last cell element of 'a'. But what I want is:
>> a
a =
{1x1 cell} {1x1 cell} {1x1 cell} {1x1 cell} {1x1 cell}
>> [a{:}]
ans =
[1] [2] [3] [4] [5]
I cannot move a = cell(1, nr) out of the for loop because in my real work I do not know how many iterations I will do. Any ideas? Thanks!
5 个评论
a = cell(1, nr)
is what is causing you to only have the last result - you keep recreating your cell array and throwing away the previous one.
You can concatenate e.g.
a = [a, someNewCell];
or better, if you can estimate an upper bound on your number of iterations create a cell array of that size first and then just assign to it and delete any empty cells at the end. Dynamically growing an array is slow and especially a cell array. Everything involving cell arrays tends to be slow.
Xh Du
2017-6-15
Adam
2017-6-15
Well, it can be a dynamically calculated size, it doesn't have to be a hard-coded upper bound.
Xh Du
2017-6-15
Adam
2017-6-15
I mean the upper bound estimate. Based on knowledge of your algorithm you should be able to come up with some calculation that at least estimates the maximum size. If your algorithm can potentially run to infinity then that is a problem in itself.
Obviously the upper bound will leave lots of empty cells in a realistic run though.
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!