フィルターのクリア

pre-allocation in loop

3 ビュー (過去 30 日間)
federico nutarelli
federico nutarelli 2022 年 12 月 16 日
コメント済み: Stephen23 2022 年 12 月 16 日
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()?

採用された回答

Sabin
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
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
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)}={}
MATRICI_SIMULATE_nonan = 3×2 cell array
{0×0 double} {0×0 double} {0×0 double} {0×0 double} {0×0 double} {0×0 cell }
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
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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by