Initializing a cell array in matlab ?

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 Commenti

This is not a structure, it's a cell array.
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?

Accedi per commentare.

 Risposta accettata

Jan
Jan il 24 Lug 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 Commenti

Thanks
@Jan man, I love your profile picture, when you see it, you know is a good answer.
Jan
Jan il 25 Giu 2021
@Pablo Nanez: Thank you :-) I'm happy if my answers help other Matlab users.
"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.
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.

Accedi per commentare.

Categorie

Richiesto:

il 23 Lug 2015

Commentato:

Jan
il 14 Feb 2022

Community Treasure Hunt

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

Start Hunting!

Translated by