Graphing .m file returning blank figure

I have a .m file that gives a euler approximation ,
function yout=euler1(t0,y0,tfinal,h,f)
y=y0;
yout=y;
for n=t0:0.01:tfinal-h;
y=y+(h.*f(n,y));
end
yout=y;
end
I am trying to graph the approximated y values over t (attempt is below) , but running it, I always get a blank figure.
t=-3:0.01:4;
t0=-3;
y0=2.5;
tfinal=4;
h=0.01;
f=@(t,y)t.*(y-2).*(log(abs(y))-1);
figure;hold on
plot(t,euler1(t0,y0,tfinal,h,f))
Is there a way to make such a graph where the y values that are approximated by the .m file are plotted to their corresponding t values?

4 Kommentare

Adam Danz
Adam Danz am 18 Sep. 2019
Have you looked at the output to your euler1() function? It produces a scalar value (1 value, not a vector of values). 't' is a vector so when you try to plot the vector and scalar you just end up with an empty figure.
The for-loop in your euler1() function is overwriting the value on each iteration. If you save that value on each iteration it will return a vector.
Walter Roberson
Walter Roberson am 18 Sep. 2019
You never pass t to the function. You should be looping passing each t value in turn, as tfinal probably.
Andre Metzger
Andre Metzger am 19 Sep. 2019
Adam, how would you save the value on wach iteration to get the vector?
I'm not sure what your eurler1 function is supposed to be doing. 'y' changes on each iteration and I'm not sure how that's supposed to produce your output vector.
This is generally how you save variables within a loop but it's very likely you need additional changes in that function.
function yout=euler1(. . .)
n = t0:0.01:tfinal-h;
yout = zeros(size(n));
for i = 1:numel(n)
yout(i)= . . .;
end
end

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Ankit
Ankit am 19 Sep. 2019
Bearbeitet: Ankit am 19 Sep. 2019

0 Stimmen

Hello Andre,
There is problem in your code. You are not storing y values.
function yout=euler1(t0,y0,tfinal,h,f)
y=y0;
yout(1)=y;
i = 1;
for n=t0:0.01:tfinal-h
y=y+(h.*f(n,y));
yout(i+1)=y;
i=i+1;
end
end
t=-3:0.01:4;
t0=-3;
y0=2.5;
tfinal=4;
h=0.01;
f=@(t,y)t.*(y-2).*(log(abs(y))-1);
figure;hold on
plot(t,euler1(t0,y0,tfinal,h,f))
Are you expecting similar curve?
Regards
Ankit

2 Kommentare

Don't forget to pre-allocate the loop variables. The i=i+1 iteration is unnecessary in a for-loop.
function yout=euler1(t0,y0,tfinal,h,f)
y=y0;
n=t0:0.01:tfinal-h;
yout = [y,zeros(size(n))];
for i = 1:numel(n)
y=y+(h.*f(n(i),y));
yout(i+1)=y;
end
end
Ankit
Ankit am 19 Sep. 2019
thanks Adam (y)

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Line Plots finden Sie in Hilfe-Center und File Exchange

Produkte

Version

R2019b

Gefragt:

am 18 Sep. 2019

Kommentiert:

am 19 Sep. 2019

Community Treasure Hunt

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

Start Hunting!

Translated by