Dan
Dan

Reputation: 13

How to vectorize double for loop in MATLAB?

i have a code that averages 4 adjacent values into the elements with double loop, i want to vectorize it how can i achieve this ?

  for i=2:99
        for j=2:99
        T1(i,j)= (T0(i+1,j) + T0(i-1,j) + T0(i,j+1) + T0(i,j-1))/4;   %adjacent units avarage
        end
  end

Upvotes: 1

Views: 146

Answers (1)

Rotem
Rotem

Reputation: 32144

Here is a vectorized version of your code:

T1(2:end-1, 2:end-1) = (T0(3:end, 2:end-1) + T0(1:end-2, 2:end-1) + T0(2:end-1, 3:end) + T0(2:end-1, 1:end-2))/4;

Following code sample verifies the vectorized code gives the same result as the loops:

T0 = imresize(im2double(imread('cameraman.tif')), [100, 100]); %Read image - used as input for the test.

T1 = T0;
for i=2:99
    for j=2:99
        T1(i,j)= (T0(i+1,j) + T0(i-1,j) + T0(i,j+1) + T0(i,j-1))/4;   %adjacent units avarage
    end
end

T2 = T0;
T2(2:end-1, 2:end-1) = (T0(3:end, 2:end-1) + T0(1:end-2, 2:end-1) + T0(2:end-1, 3:end) + T0(2:end-1, 1:end-2))/4;

disp(['Maximum difference = ', num2str(max(abs(T1(:) - T2(:))))]);

Using imfilter (or conv2):
Your code is equivalent to convolution of T0 and [0,1,0;1,0,1;0,1,0]./4 as mentioned by Daniel.
The margins result are different - I replaced the margins with the margins of T0.

%Filter kernel:
h = [0 1 0
     1 0 1
     0 1 0]/4;

T3 = imfilter(T0, h);

T4 = T0;
T4(2:end-1, 2:end-1) = T3(2:end-1, 2:end-1); %Fix the margins.

disp(['Maximum T4 difference = ', num2str(max(abs(T1(:) - T4(:))))]);

Upvotes: 1

Related Questions