Code takes too long to run
Code takes too long to run
(OP)
I am fairly new to matlab, and I have written some code to process some image data. My code works fine, except one of the early steps takes an extremely long time to compute. I have a 3 column matrix with approximately 1.4 million rows and I am performing the following code on that matrix:
k=1;
SIZE0=size(Scan);
N=SIZE0(1,1);
for i=1:N
if (Scan(i,1)>=minx) && (Scan(i,1)<=maxx) && (Scan(i,2)>=miny) && (Scan(i,2)<=maxy)
Scanx(k,1)=Scan(i,1);
Scanx(k,2)=Scan(i,2);
Scanx(k,3)=Scan(i,3);
k=k+1;
end
end
I couldn't think of another way to write this for loop, but its too slow. Is there a faster way? Thank you for your help.
-Michael
k=1;
SIZE0=size(Scan);
N=SIZE0(1,1);
for i=1:N
if (Scan(i,1)>=minx) && (Scan(i,1)<=maxx) && (Scan(i,2)>=miny) && (Scan(i,2)<=maxy)
Scanx(k,1)=Scan(i,1);
Scanx(k,2)=Scan(i,2);
Scanx(k,3)=Scan(i,3);
k=k+1;
end
end
I couldn't think of another way to write this for loop, but its too slow. Is there a faster way? Thank you for your help.
-Michael





RE: Code takes too long to run
Scanx(k,2)=Scan(i,2);
Scanx(k,3)=Scan(i,3);
could be written more concisely, see the help intro. I doubt that will have much bearing on the speed of the thing though.
breaking the IF up into a cascade of 4 IFs MAY be faster, depending on how Matlab evaluates IF. I expect the Help explains that as well.
Cheers
Greg Locock
SIG:Please see FAQ731-376: Eng-Tips.com Forum Policies for tips on how to make the best use of Eng-Tips.
RE: Code takes too long to run
- It seems to me that i and k will always be the same.
- Scanx() is growing each time you add a new row. If you pre-allocate before you start the loop, you'll see a big speedup
Scanx=zeros(size(Scan);
% rest of code.
-----------
However, since you are using Matlab, why not use it in anger:
- Look up "logical indexing". You can use it to eliminate the if() test.
- Think about vectorizing this. If can operate on the entire Scan matrix in one go, it should speed things up.
- Steve
RE: Code takes too long to run
I would try to write a simply logic function, say:
function [output]=logic(x,y,minx,maxx,miny,maxy)
if(x>=minx) && (x<=maxx) && (y>=miny) && (y)<=maxy)
output=1
else
output=0
end
Then you can run your m-file:
for i=1:size(Scan,1)
temp(i,1)=logic(Scan(i,1),Scan(i,2),minx,maxx,miny,maxy)
end
Scanx=Scan(find(temp),:)
You can use the following to determine how long your analysis is taking:
% At the first command line
tic;fprintf('Analysis time...');
% At the final command line
t=toc;fprintf('%5.2f sec\n',t);
RE: Code takes too long to run
% Just in case
clear Scanx
% Locate which rows to copy
idx = Scan(:,1)>=minx & Scan(:,1)<=maxx & Scan(:,2)>=miny & Scan(:,2)<=maxy;
% Copy them
Scanx(idx,:)=Scan(idx,:)
- Steve
RE: Code takes too long to run
- Steve