dada
dada

Reputation: 1493

Vectorize a code in Matlab

I wrote a function in Matlab that takes an image 'I' and two lengths in entries, and returns an image 'output' with same size as I in which pixels of I have been translated according to the length entries. The translation performed is cyclic, that is when a translated pixel goes d pixels beyond one of the dimensions of I, it is placed at position d in the axis related to this dimension.

This function uses two for loops and I would like to vectorize it in order to be executed in a faster way.

function [ output ] = translated(I,horizontal_translation, vertical_translation)

output=I;
[H , W]=size(I);
sx=horizontal_translation; sy=vertical_translation;
for i=1:H
    for j=1:W
        if i+sx>H
            i_=mod(i+sx,H);
        else
            i_=i+sx;
        end
        if j+sy>W
            j_=mod(j+sy,W); 
        else
            j_=j+sy; 
        end
        output(i_,j_)=I(i,j);
    end
end

end

Upvotes: 0

Views: 36

Answers (1)

Ben Voigt
Ben Voigt

Reputation: 283863

The relationship of input to output is always as follows:

 1  |  2
----+----
 3  |  4

to

 4  |  3
----+----
 2  |  1

So you can do that with four sliced assignments.

All that remains is figuring out the size of each of the blocks, which are just sx and H - sx, resp sy and W - sy.

The best option of all is to just call the circshift function provided by MATLAB that does this for you.

Upvotes: 1

Related Questions