Vector expansion

1 次查看(过去 30 天)
Karthik Uthaman
Karthik Uthaman 2011-10-3
I need a huge vector which will expand. I am working on a image processing assignment. Where i have to find the neighbours of a pixel and maintain them in a sparse matrix
My code looks like this. But its really long time to execute.
f=zeros(H*W,1);
g=zeros(H*W,1);
s=zeros(H*W,1);
a=speye(H*W,H*W);
[f,g,s]=find(a);
[m,n]=size(a);
im2var = zeros(H,W);
im2var(1:H*W) = 1:H*W;
B=zeros(H*W,1);
e=length(f)+1;
for i=1:H
for j=1:W
if mask_s(i,j) == 1
if i+1 <= H && j+1 <=W && i-1 >= 1 && j-1 >= 1
for k=1:4
f(e+k-1) = e;
s(e+k-1) = -1;
end
g(e)=im2var(i+1,j);
g(e+1)=im2var(i,j+1);
g(e+2)=im2var(i-1,j);
g(e+3)=im2var(i,j-1);
f(e+4)=e;
g(e+4)=im2var(i,j);
s(e+4)=neighbour;
else
f(e+4)=e;
g(e+4)=im2var(i,j);
s(e+4)=1;
end
else
f(e+4)=e;
g(e+4)=im2var(i,j);
s(e+4)=1;
end
e = e+1;
end
disp((sprintf('\n %d, %d \n',i,j)));
end
A=sparse(f,g,s,m,n);
I need to be able to access my vectors f,g,s faster!! Please suggest what can be done to expand the vectors faster or to access them in a different way.
Thanks in advance! :)
  3 个评论
Walter Roberson
Walter Roberson 2011-10-3
I suggest you start by profiling your code to determine where the bottle-necks are.
Jan
Jan 2011-10-3
BTW: "im2var = zeros(H,W); im2var(1:H*W) = 1:H*W;" ==> more efficient:
"im2var = reshape(1:H*W, H, W)".

请先登录,再进行评论。

回答(1 个)

Walter Roberson
Walter Roberson 2011-10-3
One thing that I can advise is that if you have a condition that is rarely true compared to your number of loop iterations, and whose truth can be predicated from your loop variables, then it is often faster to break the situation down in to cases, with the main loop set up to handle the common situation, and an additional loop (or loops) proceeding or following loop added to process the exceptions. In this way, you do not end up testing the condition over and over again.
Consider, for example, the effect on the body of the main loop if instead of using
for i=1:H
for j=1:W
you were to use
for i=2:H-1
for j=2:W-1
Also, I get the impression that you are growing vectors inside the loop. I believe that if you were to narrow the main loop limits as per above, then the loops would grow by a length you could precalculate: namely by the number of mask entries in that range that are 1. Especially if the only alternative mask value is 0, you could calculate that before the loop via
sum(sum(mask_s(2:end-1,2:end-1)))
Pre-grow your vectors accordingly.

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by