# pre-allocation in loop

1 Ansicht (letzte 30 Tage)
federico nutarelli am 16 Dez. 2022
Kommentiert: Stephen23 am 16 Dez. 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()?
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Akzeptierte Antwort

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

Melden Sie sich an, um zu kommentieren.

### Weitere Antworten (1)

Stephen23 am 16 Dez. 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
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

R2020b

### Community Treasure Hunt

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

Start Hunting!

Translated by