MATLAB: Want to speed up the code

blurringconvolutiondigital image processingImage Processing Toolboxspatial filtering

I want to speedup the code. Currently it takes approximately up to 10sec for 4608*3056 resolution image. I want to reduce the processing time as low as possible. Kindly respond me how.
%%PROCESSING IN VERTICAL DIRECTION
diff = 0;
sum = 0;
total = 0;
ver_max = 0;
max = 0;
diff = uint32(diff);
for i = 2:cols
sum = 0;
for j = 2:rows
if(I(j, i) > I(j-1, i))
diff = uint32(I(j, i) - I(j-1, i));
else
diff = uint32(I(j-1, i) - I(j, i));
end
if(diff > 20)
sum = sum + diff;
end
end
ver1(i) = sum;
% Find Peak Value

if(sum > max)
ver_max = i;
max = sum;
end
total = total + sum;
end
avg = total / cols;
subplot(3,1,1);
plot (ver1);
%%Smoothing by Low Pass Filter

sum = 0;
ver = ver1;
for i = 21:(cols-21)
sum = 0;
for j = (i-20):(i+20)
sum = sum + ver1(j);
end
ver(i) = sum / 41;
end
subplot(3,1,2);
plot (ver);
%%Filter out Low Threshold Values

for i = 1:cols
if(ver(i) < avg)
ver(i) = 0;
for j = 1:rows
I(j, i) = 0;
end
end
end
subplot(3,1,3);
plot (ver);
%%PROCESSING IN HORIZONTAL DIRECTION
diff = 0;
total = 0;
diff = uint32(diff);
max = 0;
horz_max = 0;
for i = 2:rows
sum = 0;
for j = 2:cols
if(I(i, j) > I(i, j-1))
diff = uint32(I(i, j) - I(i, j-1));
end
if(I(i, j) <= I(i, j-1))
diff = uint32(I(i, j-1) - I(i, j));
end
if(diff > 20)
sum = sum + diff;
end
end
hor1(i) = sum;
% Find Peak Value
if(sum > max)
horz_max = i;
max = sum;
end
total = total + sum;
end
average = total / rows;
subplot(3,1,1);
plot (hor1);
%%Smoothing by Low Pass Filter
sum = 0;
horz = hor1;
for i = 21:(rows-21)
sum = 0;
for j = (i-20):(i+20)
sum = sum + hor1(j);
end
horz(i) = sum / 41;
end
subplot(3,1,2);
plot (horz);
%%Filter out Low Threshold Values
for i = 1:rows
if(horz(i) < avg)
horz(i) = 0;
for j = 1:cols
I(i, j) = 0;
end
end
end
subplot(3,1,3);
plot (horz);

Best Answer

DON'T USE sum AS THE NAME OF ONE OF YOUR VARIABLES! It's the name of an important built in function and you just destroyed it.
Get rid of your for loops and use conv:
kernel = ones(1, windowWidth) / windowWidth;
blurredSignam = conv(signal, kernel, 'same');
There is also a conv2 version for 2D blurring and sharpening if you want it.