pre-allocation in loop

8 views (last 30 days)
federico nutarelli
federico nutarelli on 16 Dec 2022
Commented: Stephen23 on 16 Dec 2022
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()?

Accepted Answer

Sabin
Sabin on 16 Dec 2022
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 Comments
Walter Roberson
Walter Roberson on 16 Dec 2022
MATRICI_SIMULATE_nonan(N_RIPETIZIONI,size(colonna_i,2)) = {};
perhaps? Or
[MATRICI_SIMULATE_nonan{N_RIPETIZIONI,size(colonna_i,2)}] = deal({});
Stephen23
Stephen23 on 16 Dec 2022
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.

Sign in to comment.

More Answers (1)

Stephen23
Stephen23 on 16 Dec 2022
"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

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!