How to use multiple variables in a for loop?
6 views (last 30 days)
Show older comments
Hey I was wondering if we could declare multiple variables in the declaration of the for loop while declaring it
Here is an example code:
%To make a general filter design that supports any mask size
clc;
clearvars;
a=imread('pout.tif');%Reads the image
an=imnoise(a,'gaussian');% adds noise
m=input('enter mask size: ');
n=m^2; % n contains the number of elements in the mask
o=round(m/2); % this value is used to iterate through the loop and image matrix
p=o-1; % this value is also used to iterate o,p are unique to a specific mask
[row,col]=size(an);
b=zeros(row-o,col-o); % while performing filtering outer most pixels get removed from both row and column
mask=zeros(m);
for x=1:n
mask(x)=1/n; %Basically the mask will contain a average terms i.e for 3x3 mask each term will be 1/9
end
for x=o:row-o+1
for y=o:col-o+1
c=0;
for i=-p:p
for j=-p:p
c=c+an(x+i,y+i)*mask(1); %%%%%Ideally we should be iterating through each term of the mask
%%%%%%but all terms in mask are equal so I have taken a single term.
end
end
b(x-p,y-p)=c;
end
end
figure;
subplot(2,2,1);
imshow(a);
title('Orginal');
subplot(2,2,2);
imshow(an);
title('Image with gaussian noise');
subplot(2,2,3:4);
imshow(uint8(b));
title('LowPass filtered');
>The lines of code which contain multiple number of %%% consist of the highlighted part
One possible solution the achieve the above stated issue was to :
for i=-p:p %can we say for i,k=-p,1:p,m
for j=-p:p %can we say for j,l=-p,1:p,m
c=c+an(x+i,y+i)*mask(k,l);%make variables k,l which iterates through (1,1) to (5,5) of the mask in case
% of mask having size 5x5
end
end
I am not sure if something like this is allowed or possible in matlab.
Appreciate your reply.
Please ask me if I am not clear enough:)
2 Comments
dpb
on 5 Aug 2018
mask=zeros(m);
for x=1:n
mask(x)=1/n; %Basically the mask will contain a average terms i.e for 3x3 mask each term will be 1/9
end
What the above produces is NOT what the comment says...the above is simply
mask=1./(1:n);
or the sequence of 1, 1/2, 1/3, ... 1/n. Which is really wanted; either way there's no need for a loop; the alternative per the comment would be
mask=ones(n)/n;
I didn't read the rest in detail but strikes me what you're trying to do is already done for you...see filter2 or the link therein to conv2.
For image processing there are probably other functions specifically for images that do same/similar...I don't have it so am not that familiar with its content.
Answers (0)
See Also
Categories
Find more on Author Block Masks in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!