function needs to return multiple outputs but only returns one, leads to incorrect plot

1 view (last 30 days)
I'm new to matlab and having trouble plotting a solution to a differential equation. The task is to use Euler's Method to reach and answer, as well as solving directly, then overlaying the two solutions on one plot. I was able to plot Euler's correctly, but my direct solution doesn't work because instead of returning one output(y) for each input(t) it only returns a single output(y(t_last))
%Euler's method
t=zeros(51,1);
y1=zeros(51,1);
t(1)=0;
y1(1)=200;
for i=1:50
t(i+1)=t(i)+.5;
y1(i+1)=y1(i)+.01.*(.65*(1-((y1(i)/(5.4))))).*y1(i);
end
%direct solution
y2=zeros(51,1);
y2(1)= 200;
y2= (-1.03*5.4*exp(1).^(.65*t))/(1-1.03*exp(1).^(.65*t));
%plot
plot(t,y1,t,y2)
Nothing I do seems to work, please help! Note: the direct solution plot leads to the correct answer but only for the last value of t. all other points of t do not follow the right trend.

Answers (1)

Star Strider
Star Strider on 23 Jun 2018
If your function returns more than one output, you have to ask for as many of them as you need in your calling code.
Example
Function definition:
function [t,y] = myFunction(a,b)
...
end
Function call:
[T,Y] = myFunction(A,B);
Also, you need to vectorize ‘y2’ to get the result you probably want:
y2= (-1.03*5.4*exp(0.65*t))./(1-1.03*exp(0.65*t));

Categories

Find more on Programming 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!