Using Vectorization to Calculate New Values Based on Surrounding Values

9 views (last 30 days)
Pardon any mistakes, I'm going through a massive panic attack at the moment with the stress of trying to solve this the last 4+ hours.
I have a project for my programming class that wants me to write a bunch of functions to assist an edge finding function. It has to all be vectorized, ie no iteration or selection. And I'm failing to vectorize the very first function.
The task in question:
The idea is that all the values in a matrix are given a weighted average based on given matrix W. I've already successfully implemented this code with iteration here:
W = [10/222 27/222 10/222;
27/222 74/222 27/222;
10/222 27/222 10/222];
for i=2:size(bw_im,1)-1
for j=2:size(bw_im,2)-1
A=bw_im(i-1:i+1, j-1:j+1);
bw_im(i,j)=sum(sum(A.*W));
end
end
bw_smooth=bw_im;
This successfully outputs the values the full instructions ask for. However, I've been unable to properly vectorize it. The best I've gotten is cutting out the iteration with this
bw_im(2:size(bw_im,1)-1,2:size(bw_im,2)-1)=
Which means it'll only overwrite the non-edge values. Other than that, I'm completely stumped. Please help, I'm panicking at the moment as there is still so much more to do.

Answers (1)

Image Analyst
Image Analyst on 24 Mar 2018
Just use conv2() with the valid option and then paste it onto a copy of the original. It's 3 lines of code. Hint:
conv2Image = conv2(A, w, 'valid');
result = A; % Initialize
result(2:............) = conv2Image; % Paste
I'll let you figure out the indexes in the third line to complete it. Should take you less than a minute, not 4 hours, once you realize what they are describing is convolution (actually correlation but with a symmetrical kernel correlation is the same as convolution).
If you can't use conv2() and need to do it yourself, I attach a very inefficient manual way of doing the scanning with a 4-nested for loop, though it's not recommended. I recommend using conv2 because it's highly efficient and optimized.
  9 Comments
Sam Ajami
Sam Ajami on 24 Mar 2018
Welp I figured it out, it's the stupidest piece of code ever but it works
bw_im(2:end-1,2:end-1)=bw_im(1:end-2,1:end-2)*10/222+bw_im(1:end-2,2:end-1)*27/222+bw_im(1:end-2,3:end)*10/222+bw_im(2:end-1,1:end-2)*27/222+bw_im(2:end-1,2:end-1)*74/222+bw_im(2:end-1,3:end)*27/222+bw_im(3:end,1:end-2)*10/222+bw_im(3:end,2:end-1)*27/222+bw_im(3:end,3:end)*10/222;
Image Analyst
Image Analyst on 24 Mar 2018
There are differences between your method and the one I suggested. See attached code.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!