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.
0 个评论
回答(1 个)
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
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!