Need assistance with incorrect output in plot.

Hi all. I am working on a class project that takes a set of four first order equations and integrates them into a plot. The plot should appear as this below but my graph is totally different and I am not sure what is causing the issue. Can anyone point out where I am going wrong? I am including my full code below. Thanks in advance
%% Creating custom R-K Integrator
clear
clc
dt=0.0001 %0.01 sec was used initially,
x_vect=[0,0,0,0]; %Initial Conditions
t_span=[0:dt:2];
npoints=length(t_span);
x_dot = @deriv
t0=0;
t(1)=t0;
x_answer(1)=x_vect(1,4);% Initialize answer vector.
for i=1:npoints
t(i+1) = t(i)+dt; %update t, this value will not be used until next iteration.
x_vect = integ(x_vect,x_dot,t(i),dt);
x_answer(i+1)=x_vect(1,4);
t0=t(i);
end
plot(t,x_answer)
function out=integ(x_vect,x_dot,t,dt) %fourth order runge kutta
%out=x_vect+x_dot*dt;
k1=x_dot(t,x_vect)*dt;
k2=x_dot(t+dt/2,x_vect+k1/2)*dt;
k3=x_dot(t+dt/2,x_vect+k2/2)*dt;
k4=x_dot(t+dt,x_vect+k3)*dt;
out=x_vect+1/6*(k1+2*k2+2*k3+k4);
end
function out=deriv(t,y_init)
out(1) = y_init(2);
out(2) = y_init(3);
out(3) = y_init(4);
out(4) = -206*y_init(4)-1341.4*y_init(3)-848.4*y_init(2)+60000;
end

5 Kommentare

darova
darova am 28 Mär. 2021
Please show original equation
Sean Sweeney
Sean Sweeney am 28 Mär. 2021
Sean Sweeney
Sean Sweeney am 28 Mär. 2021
this is the 4th order DE we were given which should output the above graph. However my code it outputing a drastically different plot
darova
darova am 29 Mär. 2021
what is x_dot?
darova
darova am 29 Mär. 2021
x_dot according to my reacher is supposed to represent the derivitive.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

darova
darova am 29 Mär. 2021

0 Stimmen

Try to change this part
x_answer = zeros(npoints,4); % preallocate answer vector
x_answer(1,:) = x_vect(1,4); % Initialize answer vector.
And this part inside for loop
x_answer(i+1,:) = x_vect

1 Kommentar

Sean Sweeney
Sean Sweeney am 29 Mär. 2021
x_dot = @deriv
t0=0;
t(1)=t0;
x_answer = zeros(npoints,4);
x_answer(1,:) = x_vect(1,4);
for i=1:npoints
t(i+1) = t(i)+dt; %update t, this value will not be used until next iteration.
x_vect = integ(x_vect,x_dot,t(i),dt);
x_answer(i+1,:) = x_vect
t0=t(i);
end
The bold is what I updated from the original code, but it just ran forever until I manually ended the script. Was this the change you were suggesting?

Melden Sie sich an, um zu kommentieren.

Gefragt:

am 27 Mär. 2021

Kommentiert:

am 29 Mär. 2021

Community Treasure Hunt

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

Start Hunting!

Translated by