How to Preallocate for speed?

2 次查看(过去 30 天)
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

采纳的回答

David Hill
David Hill 2022-3-8
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by