Effacer les filtres
Effacer les filtres

How to Preallocate for speed?

2 vues (au cours des 30 derniers jours)
Madhura Ramani
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

Réponse acceptée

David Hill
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
  1 commentaire
Madhura Ramani
Madhura Ramani le 17 Mar 2022
Thank You. It worked !!!

Connectez-vous pour commenter.

Plus de réponses (0)

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!

Translated by