Initializing a cell array in matlab ?
조회 수: 211 (최근 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에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!