pre-allocation in loop
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Sabin
le 16 Déc 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 commentaires
Walter Roberson
le 16 Déc 2022
MATRICI_SIMULATE_nonan(N_RIPETIZIONI,size(colonna_i,2)) = {};
perhaps? Or
[MATRICI_SIMULATE_nonan{N_RIPETIZIONI,size(colonna_i,2)}] = deal({});
Stephen23
le 16 Déc 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)}={}
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.
Plus de réponses (1)
Stephen23
le 16 Déc 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 commentaires
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!