I need help with Matlab vectorization of this code

advertisements

I am new on MatLAB, i don't know proper basics of vectorization.. I am trying to vectorize this function.

function  indc  =  PatchSearch(X, row, col, off, nv, S, I)

[N M]   =   size(I);
f2      =   size(X,2);

rmin    =   max( row-S, 1 );
rmax    =   min( row+S, N );
cmin    =   max( col-S, 1 );
cmax    =   min( col+S, M );

idx     =   I(rmin:rmax, cmin:cmax);
idx     =   idx(:);
B       =   X(idx, :);
v       =   X(off, :);

dis     =   (B(:,1) - v(1)).^2;
for k = 2:f2
    dis   =  dis + (B(:,k) - v(k)).^2;
end
dis   =  dis./f2;
[val,ind]   =  sort(dis);
indc        =  idx( ind(1:nv) );
%indc = idx(dis<250);

I need help from some experts for vectorizating this function Thanks


You can replace the following loopy portion of your code -

dis     =   (B(:,1) - v(1)).^2;
for k = 2:f2
    dis   =  dis + (B(:,k) - v(k)).^2;
end

With this bsxfun implementation -

dis = sum(bsxfun(@minus,B,v).^2,2);

The assumption here is that f2 is the number of columns in B, which is the same as the number of elements in v and looking at your code the way B and v are initialized, that seems to be quite right.