Apetro
Apetro

Reputation: 63

Matlab Differential Equations Euler’s method

I need help plotting a differential equation ... it keeps coming out all funky and the graph is not what it's supposed to look like.

function [dydt] = diff(y,t)

dydt = (-3*y)+(t*(exp(-3*t)));

end

tI = 0;
yI = -0.1;
tEnd = 5;
dt = 0.5;

t = tI:dt:tEnd;
y = zeros(size(t));
y(1) = yI;

for k = 2:numel(y)
    yPrime = diff(t(k-1),y(k-1));
    y(k) = y(k-1) + dt*yPrime;
end

plot(t,y)
grid on
title('Engr')
xlabel('Time')
ylabel('y(t)')
legend(['dt = ' num2str(dt)])

That's my code, but the graph is not anything like what it's supposed to look like. Am I missing something like an index for the for statement?

Edit

I am getting an error:

Error using diff
Difference order N must be a positive integer scalar.

Error in diff3 (line 12)
    yPrime = diff(t(k-1),y(k-1));

Upvotes: 0

Views: 2289

Answers (1)

user3717023
user3717023

Reputation:

After fixing the errors pointed out by Danil Asotsky and horchler in the comments:

  1. avoiding name conflict with built-in function 'diff'
  2. changing the order of arguments to t,y.
  3. decreasing the time-step dt to 0.1
  4. converting ODE right-hand side to an anonymous function

(and removing unnecessary parentheses in the function definition), your code could look like this:

F = @(t,y) -3*y+t*exp(-3*t);

tI = 0;
yI = -0.1;
tEnd = 5;
dt = 0.1;

t = tI:dt:tEnd;
y = zeros(size(t));
y(1) = yI;

for k = 2:numel(y)
    yPrime = F(t(k-1),y(k-1));
    y(k) = y(k-1) + dt*yPrime;
end

plot(t,y)
grid on
title('Engr')
xlabel('Time')
ylabel('y(t)')
legend(['dt = ' num2str(dt)])

which performs as expected:

output

Upvotes: 1

Related Questions