You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matlab实现向前欧拉方法遇下标错误求助:下标需为正整数或逻辑值

Fixing the "Subscript indices must either be real positive integers or logicals" Error in Your Forward Euler MATLAB Code

Hey there, let's break down what's causing this error and fix your Forward Euler implementation step by step!

The Root of the Problem

MATLAB uses 1-based indexing for arrays—meaning the first element of any array is always at index 1, not 0. Your code tries to access t(0) and y(0), which are invalid indices because 0 isn't a positive integer. That's exactly why you're getting that error on line 5 (and you'd hit the same issue on the y(0)=y0 line too).

Corrected Code

Here's the fixed version of your function, with comments explaining the changes:

function y = ForwardEulerMethod(f,y0,T,N)
    h = T/N;
    t = zeros(N+1,1);
    % Loop from 1 to N+1 (valid indices) instead of 0 to N
    for i = 1:N+1
        t(i) = (i-1)*h;  % Shift to get t(1)=0, t(2)=h, ..., t(N+1)=T
    end
    y = zeros(N+1,1);
    y(1) = y0;  % Use index 1 for the initial condition
    % Loop from 2 to N+1 to compute subsequent values
    for i = 2:N+1
        y(i) = y(i-1) + h*f(t(i-1), y(i-1));
    end
end

Key Changes Explained

  • First loop adjustment: We start i at 1 instead of 0, and calculate t(i) as (i-1)*h. This gives us the correct time points: t(1) = 0, t(2) = h, all the way to t(N+1) = T.
  • Initial condition index: We assign y0 to y(1) instead of y(0)—this is the valid first element of the y array.
  • Second loop adjustment: We start i at 2 (since y(1) is already set) and go up to N+1, ensuring we always access valid indices i-1 (which starts at 1) and i.

Quick Test to Verify

You can test the function with a simple ODE like dy/dt = y (solution y(t) = e^t) to make sure it works:

f = @(t,y) y;
y0 = 1;
T = 1;
N = 10;
y = ForwardEulerMethod(f,y0,T,N);
% Compare with analytical solution
t = linspace(0,T,N+1);
y_analytical = exp(t);
plot(t,y,'o-',t,y_analytical,'--');
legend('Forward Euler','Analytical Solution');

This should plot the Euler approximation alongside the exact solution, confirming the code runs without errors.

内容的提问来源于stack exchange,提问作者Matt Robbins

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:01:49