How to run two for loops

11 views (last 30 days)
Hi,
Here is a matlab code:
*******************************
fx = 2:2:2^5;
fy = 2;
a=128;
b=128;
c=512;
[x,y] = meshgrid(linspace(-1,1,128));
circ=sqrt(x.^2+y.^2)<1;
for j1 = numel(fx):-1:1
h{j1} = circ.*cos(pi*(x*fx(j1) + y*fy));
end
M = cell(c/a);
M(:) = h;
M = cell2mat(M');
figure(1)
imagesc(M),colormap gray; axis image; axis off
title('Array Of 4x4 Holograms'); %Fourier Transform
z=fftshift(fft2(M,512,512));
q=abs(z); figure(2)
imagesc(q); colormap gray; axis image; axis off
title('Focal Spots Of Grating Array');
**********************
With the above code, there is variation only in the 'fx' value, but if I want to change the value of 'fy' also, then how to do that? More precisily, I want to run a for loop of this kind(so that instead of obtaining 1 row of 16 spots, I obtain 2 rows of 4x4 spots):
h1=circ.*(cos((x*pi*fx1)+(y*pi*fy1)));
h2=circ.*(cos((x*pi*fx2)+(y*pi*fy1)));
h3=circ.*(cos((x*pi*fx3)+(y*pi*fy1)));
h4=circ.*(cos((x*pi*fx4)+(y*pi*fy1)));
h5=circ.*(cos((x*pi*fx1)+(y*pi*fy2)));
h6=circ.*(cos((x*pi*fx2)+(y*pi*fy2)));
h7=circ.*(cos((x*pi*fx3)+(y*pi*fy2)));
h8=circ.*(cos((x*pi*fx4)+(y*pi*fy2)));
h9=circ.*(cos((x*pi*fx1)+(y*pi*fy3)));
h10=circ.*(cos((x*pi*fx2)+(y*pi*fy3)));
h11=circ.*(cos((x*pi*fx3)+(y*pi*fy3)));
h12=circ.*(cos((x*pi*fx4)+(y*pi*fy3)));
h13=circ.*(cos((x*pi*fx1)+(y*pi*fy4)));
h14=circ.*(cos((x*pi*fx2)+(y*pi*fy4)));
h15=circ.*(cos((x*pi*fx3)+(y*pi*fy4)));
h16=circ.*(cos((x*pi*fx4)+(y*pi*fy4)));
-----------
Can anyone please help me in this regard?
Thanking You!
  3 Comments
Jan
Jan on 15 Jul 2013
@Pranjal: I've deleted the double posting. Please do not post a question several times and care about a proper formatting. When you code is not readable, you cannot expect the forum users to read it.
@dpb: Matt J can delete questions in some days also as the other editors.

Sign in to comment.

Accepted Answer

Muthu Annamalai
Muthu Annamalai on 15 Jul 2013
Edited: Muthu Annamalai on 15 Jul 2013
To do it the way you want, not my preference, you should write a double loop, and compute the index into the cell array h
For e.g.
for j1 = numel(fx):-1:1
for j2 = numel(fy):-1:1
h{(j1-1)*numel(fy) + j2 } = circ.*cos(pi*(x*fx(j1) + y*fy(j2)));
end
end
Having said that, the proper MATLAB way of writing this equation may be, to compute the frequency component matrix separately using meshgrid() once, like,
[FX,FY] = meshgrid( fx, fy )
HTH
  1 Comment
Pranjal Pathak
Pranjal Pathak on 15 Jul 2013
Sorry for my mistake. Thanks a lot for your answer, it worked.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by