For Loop/Nested Loop - using solution to previous iteration in nested loop?

Hello,
I'm trying to do a nested loop in which from the second iteration onwards the term zl of the function being iterated is substituted by the solution to the previous iteration. My code is underneath:
zl=(1/4.*((k.*a).^2))+(1j*0.6.*(k.*a));
%initiating loop
for i=2:5
for n=1:4
x(i-1)=(0.077/4)*(i-1);
S(i-1)=St*(exp(m*x(i-1)));
Z(i-1,n)=(zl(n)+B(i-1,n))./((1+zl(n))./S(i-1).*C(n));
end
end
So for the iteration 2 of Z, zl should corresponde to the first iteration of Z, for iteration 3 of Z, zl should correspond to the second iteration of Z and so forth. Hope I'm being clear. Any tips would be appreciated.

Answers (1)

Hello
You want for example in n=3 iteration zl be Z computed in n=2 iteration? But with this line your zl is the same for all iterations:
zl=(1/4*((k*a).^2))+(1j*0.6*(k*a));
You may need to write it before your loop:
%initiating loop
zl=(1/4*((k*a).^2))+(1j*0.6*(k*a));
for n=2:5
x(n)=(0.077/4)*(n-1);
S(n)=St*(exp(m*x(n-1)));
%terms for equation Z
A1=zl;
B1=(1j*(p0c./(S(n-1)))).*(tan(k*L));
C1=1;
D1=(1j*(zl./(p0c/(S(n-1))))).*(tan(k*L));
%equation Z composed of the previous terms
Z=(A1+B1)./(C1+D1);
zl=Z;
end

3 Comments

Hi Iman,
Thanks for you reply. I re-edited the post as it wasn't clear plus I made some changes for the better I think. I did have the function you mention outside the loop but it didnt look like. Still can't figure out how to use previous solutions in the next iteration.
With this code you use 1:4 elements of zl or Z but I think your zl was a vector with 10000 elements.
Before end of the loop you can use zl=Z to set the value of zl in next iteration, like my code.
Thanks for your help. Much simpler than I thought. The vector should be 10000 or any length really, I should be able to change that. Now I'm having trouble in plotting the results. I would like the final results of Z but the graph looks a bit weird. I end up with a Z matrix of Z(4,10000) so I thought I should plot(Z(1,:)) to plot the results of the first row since my code goes from the 4th iteration to the first. Any tips? cheers

Sign in to comment.

Categories

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

Asked:

on 4 Apr 2013

Community Treasure Hunt

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

Start Hunting!