Initializing a cell array in matlab ?
214 views (last 30 days)
Show older comments
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 Comments
James Tursa
on 23 Jul 2015
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?
Accepted Answer
Jan
on 24 Jul 2015
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 Comments
Jérôme
on 14 Feb 2022
"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
on 14 Feb 2022
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.
More Answers (1)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!