필터 지우기
필터 지우기

how to Vectorize this for loop?

조회 수: 2 (최근 30일)
Miguel Reina
Miguel Reina 2017년 12월 1일
편집: Miguel Reina 2017년 12월 2일
I am trying to create a full convolution without the conv2 function. For that, i would like to vectorize this nested loop.
[r,c] = size(A);% size of image A
[m,n] = size(mask);%size of the mask
ab=padarray(A,[2 2]); %Padding zeros in the original image
ab=im2double(ab);
B = zeros(r+m,c+n);
for x = 1 : r+m-1
for y = 1 : n+c-1
for i = 1 : m
for j = 1 : n
B(x, y) = B(x, y) + (ab(x+i-1, y+j-1) * mask(i, j));
end
end
end
end
  댓글 수: 2
Jos (10584)
Jos (10584) 2017년 12월 1일
Why can't you use conv2? (it is rather silly to speed up code that is not optimal)
Another question: why the fixed [2 2] padding?
Miguel Reina
Miguel Reina 2017년 12월 1일
Hi Jos, is intended to be for educational purposes. For some students is more difficult to understand some concepts packaged in one function so i want to make it easier for them and also help them with the importance of vectorization in matlab. The padding is for the same reason, to explain what happens with the borders.

댓글을 달려면 로그인하십시오.

채택된 답변

Guillaume
Guillaume 2017년 12월 1일
편집: Guillaume 2017년 12월 1일
Well, the vectorised version of your code is to use conv2! Or ifft2 the fft2 product (with suitable padding).
Otherwise, when you're trying to teach the principle of convolutions you use explicit loops as you have.
The only thing you may change would be to replace the two inner loops by a vectorised operation:
for x = 1 : r+m-1
for y = 1 : n+c-1
B(x, y) = sum(ab(x:x+m-1, y:y+m-1) .* mask)
end
end
I don't understand the fixed size padding. If you're computing a full convolution then you should indeed end up with an array of size size(ab) + size(mask) - 1 but that's because you've padded ab by size(mask).
  댓글 수: 1
Miguel Reina
Miguel Reina 2017년 12월 2일
편집: Miguel Reina 2017년 12월 2일
There must be a correction, thank you so much !
for x = 1 : r+m-1
for y = 1 : n+c-1
B(x, y) = sum(sum(ab(x:x+m-1, y:y+m-1) .* mask));
end
end

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

Community Treasure Hunt

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

Start Hunting!

Translated by