Usage Of "goto" for previous lines
1 view (last 30 days)
Show older comments
hello guys Iva had a simple but confusing question... i was writing a program for Euler's formula, then I found out Matlab doesn't have any "goto" function for refering to previous lines . i was looking for an alternate and i will appreciate it if you guys help me with this :) here's an example:
x=[0.1:0.1:1]
h=0.1
i=1
y(1)=1
Z(1)=1.1
Y(1)=1.1
%Y'=y*(x^(1/3))
while i<11
y(i+1)=y(i)+(h*(x(i)*(y(i)^(1/3))))
Z(i+1)=(x(i+1)*(y(i+1)^(1/3)))
line** y(i+1)=y(i)+(0.5*h*(Y(i)+Z(i+1)))
Y(i+1)=x(i+1)+y(i+1)
if abs(Y(i+1)-Z(i+1))>0.00000000001
Z(i+1)=Y(i+1)
goto(line**)
end
i=i+1
end
Accepted Answer
Azzi Abdelmalek
on 19 Dec 2014
Edited: Azzi Abdelmalek
on 19 Dec 2014
Insert this code
test=1;
while test==1
y(i+1)=y(i)+(0.5*h*(Y(i)+Z(i+1)))
Y(i+1)=x(i+1)+y(i+1)
if abs(Y(i+1)-Z(i+1))>0.00000000001
Z(i+1)=Y(i+1)
test=1;
else
test=0;
end
end
More Answers (1)
Stephen23
on 19 Dec 2014
Edited: Stephen23
on 20 Dec 2014
Try this:
x = 0.1:0.1:1;
h = 0.1;
y(1) = 1;
Z(1) = 1.1;
Y(1) = 1.1;
%Y'=y*(x^(1/3))
for k = 1:9
y(k+1) = y(k)+(h*(x(k)*(y(k)^(1/3))));
Z(k+1) = (x(k+1)*(y(k+1)^(1/3)));
while true
y(k+1) = y(k)+(0.5*h*(Y(k)+Z(k+1)));
Y(k+1) = x(k+1)+y(k+1);
if abs(Y(k+1)-Z(k+1))<=0.00000000001, break, end
Z(k+1) = Y(k+1);
end
end
Note that this kind of code style can easily end up in an infinite loop, so you might want to consider how to prevent this. And to be honest this looks like a good contender for some serious rewriting as proper MATLAB code, i.e. fully vectorized .
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements 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!