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

1 次查看(过去 30 天)
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.

回答(1 个)

Iman Ansari
Iman Ansari 2013-4-4
编辑:Iman Ansari 2013-4-4
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 个评论
Iman Ansari
Iman Ansari 2013-4-5
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.
catarina
catarina 2013-4-5
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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by