Matlab微分方程Euler方法

时间:2013-07-06 06:29:26

标签: matlab differential-equations

我需要帮助绘制一个微分方程......它一直都是时髦的,图形不是它看起来的样子。

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)])

这是我的代码,但图表并不像它看起来那样。我错过了for语句的索引吗?

修改

我收到错误:

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));

1 个答案:

答案 0 :(得分:0)

修复了Danil Asotsky和horchler在评论中指出的错误:

  1. 避免与内置函数'diff'的名称冲突
  2. 将参数的顺序更改为t,y
  3. 将时间步长dt减少到0.1
  4. 将ODE右侧转换为匿名函数
  5. (并删除函数定义中不必要的括号),您的代码可能如下所示:

    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)])
    

    按预期执行:

    output