pre-allocation in loop
3 次查看(过去 30 天)
显示 更早的评论
Hi all,
MATLAB is suggesting me to pre-allocate MATRICI_SIMULATE_nonan and colonna_i in the following loop:
A_nan = A~=0;
MATRICI_SIMULATE_nonan={};
for i = 1:N_RIPETIZIONI
for j = 1:size(colonna_i,2)
MATRICI_SIMULATE_nonan{i,j}=MATRICI_SIMULATE{i,j}.*A_nan;
MATRICI_SIMULATE_nonan{i,j}(MATRICI_SIMULATE_nonan{i,j} == 0) = NaN;
end
end
However I think I have already done it at least with MATRICI_SIMULATE_nonan. Am I missing something? Maybe I should use cell()?
0 个评论
采纳的回答
Sabin
2022-12-16
To preallocate memory for a cell array please check this doc page:
In your case you can do:
MATRICI_SIMULATE_nonan{N_RIPETIZIONI,size(colonna_i,2)}={};
2 个评论
Walter Roberson
2022-12-16
MATRICI_SIMULATE_nonan(N_RIPETIZIONI,size(colonna_i,2)) = {};
perhaps? Or
[MATRICI_SIMULATE_nonan{N_RIPETIZIONI,size(colonna_i,2)}] = deal({});
Stephen23
2022-12-16
This answer is fragile, inconsistent, and gives no explanation why it assigns an empty cell array in the final cell.
Lets have a look at the content of that preallocated cell array, by trying the author's code:
N_RIPETIZIONI = 3;
colonna_i = rand(1,2);
MATRICI_SIMULATE_nonan{N_RIPETIZIONI,size(colonna_i,2)}={}
Why should the last cell contain a 0x0 cell array? This is very odd, superfluous, and in some situations this inconsistency might cause problems. Best avoided.
更多回答(1 个)
Stephen23
2022-12-16
"However I think I have already done it at least with MATRICI_SIMULATE_nonan."
There is nothing like preallocation in your code.
"Am I missing something?"
Preallocation requires creating an array of the final size, which your code does not do.
"Maybe I should use cell()?"
Yes, that would be the best way. For example, something like:
MATRICI_SIMULATE_nonan = cell(N_RIPETIZIONI,size(colonna_i,2));
Your code would be clearer with a temporary variable, e.g.:
A_nan = A~=0;
MATRICI_SIMULATE_nonan = cell(N_RIPETIZIONI,size(colonna_i,2)); % preallocate!
for ii = 1:N_RIPETIZIONI
for jj = 1:size(colonna_i,2)
tmp = MATRICI_SIMULATE{ii,jj}.*A_nan;
tmp(tmp==0) = NaN;
MATRICI_SIMULATE_nonan{ii,jj} = tmp;
end
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!