Initializing a cell array in matlab ?

190 vues (au cours des 30 derniers jours)
Hesham Ismail
Hesham Ismail le 23 Juil 2015
Commenté : Jan le 14 Fév 2022
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 commentaires
Azzi Abdelmalek
Azzi Abdelmalek le 23 Juil 2015
This is not a structure, it's a cell array.
James Tursa
James Tursa le 23 Juil 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?

Connectez-vous pour commenter.

Réponse acceptée

Jan
Jan le 24 Juil 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 commentaires
Jérôme
Jérôme le 14 Fév 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
Jan le 14 Fév 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.

Connectez-vous pour commenter.

Plus de réponses (1)

Muhammad Usman Saleem
Muhammad Usman Saleem le 23 Juil 2015
use
size(cell array)
  1 commentaire
Hesham Ismail
Hesham Ismail le 24 Juil 2015
i don't think that works

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by