# Using euler's method to plot x(t) graph

5 views (last 30 days)
Kristina on 6 Oct 2022
Answered: Torsten on 6 Oct 2022
I created a code to run euler's method for the function x^3+x^2-12x. It works and everything seems to be fine, but when I try to create the x(t) graph using euler's method it does not graph the anticipated graph. The anticipated graph is the hand-drawn graph. The graph I receive is based on the codes I provided. I'm not sure where my code is maybe producing incorrect values in order to get the hand-drawn graph.
function y = eulersub(a,b)
h = 0.01;
x = -5:h:5;
y = zeros(size(x));
y(1)=-40;
n = numel(y);
for i=1:n-1
f = 3*x(i).^2+2*x(i)-12;
y(i+1) = y(i) + h * f;
end
plot(x,y)
ICs = zeros(4,1);
ICs(1) = -5;
ICs(2) = -2;
ICs(3) = 2;
ICs(4) = 5;
timeVector = linspace(0,15,1001);
vecSize = size(timeVector);
outputValues = zeros(vecSize(1));
hold on
for z=1:4
outputValues = eulersub(ICs(z), timeVector);
plot(outputValues, timeVector)
end
hold off

Torsten on 6 Oct 2022
You pass "ICs(z)" and "timeVector" to "eulersub". In the function, they get the names a and b. But a and b are never referenced in "eulersub". So for all initial conditions you pass to the function, you work with y(0) = -40 and a time interval between -5 and 5.
Maybe you mean
ICs = zeros(4,1);
ICs(1) = -5;
ICs(2) = -2;
ICs(3) = 2;
ICs(4) = 5;
timeVector = linspace(0,15,1001);
vecSize = numel(timeVector);
outputValues = zeros(4,vecSize);
for z=1:4
outputValues(z,:) = eulersub(ICs(z), timeVector);
end
plot(timeVector,outputValues)
function y = eulersub(y0,timeVector)
x=timeVector;
y = zeros(size(x));
y(1)=y0;
n = numel(y);
for i=1:n-1
f = 3*x(i).^2+2*x(i)-12;
y(i+1) = y(i) + (x(i+1)-x(i)) * f;
end
end

### Categories

Find more on Stress and Strain 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!

Translated by