Initializing a cell array in matlab ?
214 次查看(过去 30 天)
显示 更早的评论
I have a cell array like this
Columns 1 through 7
[0x1 double] [2x1 double] [2x1 double] [0x1 double] [2x1 double] [2x1 double] [2x1 double]
Columns 8 through 12
[2x1 double] [4x1 double] [3x1 double] [3x1 double] [4x1 double]
is there a way to initialize them since i don't know the size of the element (0x1double)? The only thing i know is that i have 12 elements but not the actual inner size.
2 个评论
James Tursa
2015-7-23
Often you don't need to specify the "inner size" of the cell elements since they will get replaced with something else downstream in your code. The typical practice is to leave them empty. Why do you think you need to initialize them?
采纳的回答
Jan
2015-7-24
You pre-allocate only the cell:
C = cell(1, 12);
There is no need to pre-allocate the elements of the array, because you can pre-allocate the arrays, when you create them. When you assign them to the cell element, the former contents is overwritten. Therefore pre-defining the cell elements is not a pre-allocation, but a waste of memory.
5 个评论
Jérôme
2022-2-14
"pre-defining the cell elements is not a pre-allocation, but a waste of memory."
Imagine at the end of my program we have a N×1 cell array, and in each of these cells we have a L×M double array. But in my program, I get only one row at a time from the double array, as follows:
for idx_n = 1:N
for idx_l = 1:L
var{idx_n}(idx_l,:) = my_function(idx_n,idx_l);
end
end
my_function returns a 1×M double array, and I cannot change it to get the full L×M double array directly.
We could preallocate like this:
var = cell(N,1);
for idx_n = 1:N
var{idx_n} = zeros(L,M);
end
Testing with my_function = randn(1,M); N = 12; L = 100000; M = 4;, without preallocation it takes 54 s, whereas with preallocation it takes 1.6 s.
So I would say that pre-defining the cell elements may worth it according to the context.
Jan
2022-2-14
Of coure in your code the pre-allocation is useful. An even more efficient solution:
for idx_n = 1:N
tmp = zeros(L,M);
for idx_l = 1:L
tmp(idx_l,:) = my_function(idx_n,idx_l);
end
var{idx_n} = tmp;
end
This reduces the number of accesses to the cell element.
更多回答(1 个)
另请参阅
类别
在 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!