How to Preallocate for speed?
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Madhura Ramani
le 8 Mar 2022
Commenté : Madhura Ramani
le 17 Mar 2022
I am trying to preallocate the speed in this particular code and couldn't try to get it right.
It keeps saying Index in position 2 exceeds the array bound and the preallocation doesnt seem to happen.
Do you think the code is right? Could you tell me what I am doing wrong?
Thanks in Advance
function cut_in_small_segmets
global membrane
s=size(membrane);
deltaX=round(s(2)/20);
deltaY=round(s(1)/20);
k=zeros(1000);
for i=1:deltaX
for j=1:deltaY
k=k+s;
small{k}=imadjust(membrane((i-1)*deltaY+1:i*deltaY, (j-1)*deltaX+1:j*deltaX));
%% I get error in the " small{k}=imadjust(membrane((i-1)*deltaY+1:i*deltaY, (j-1)*deltaX+1:j*deltaX));" and it says consider preallocating for speed
end
end
adjusted_pict=[small{1:19}; small{20:38}; small{39:57}; small{58:76}; small{77:95}];
s=size(adjusted_pict);
for i=1:s(1)
for j=1:s(2)
membrane(i,j)=adjusted_pict(i,j);
end
end
end
0 commentaires
Réponse acceptée
David Hill
le 8 Mar 2022
s=size(membrane);
deltaX=floor(s(2)/20);%should use floor or you will run into indexing problems below
deltaY=floor(s(1)/20);%should use floor or you will run into indexing problems below
small=cell(deltaX*deltaY);%preallocate small cell array
count=0;
for i=1:deltaX
for j=1:deltaY
count=count+1;
small{count}=imadjust(membrane((i-1)*deltaY+1:i*deltaY, (j-1)*deltaX+1:j*deltaX));
end
end
Plus de réponses (0)
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!