Matlab实现向前欧拉方法遇下标错误求助:下标需为正整数或逻辑值
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
iat1instead of0, and calculatet(i)as(i-1)*h. This gives us the correct time points:t(1) = 0,t(2) = h, all the way tot(N+1) = T. - Initial condition index: We assign
y0toy(1)instead ofy(0)—this is the valid first element of theyarray. - Second loop adjustment: We start
iat2(sincey(1)is already set) and go up toN+1, ensuring we always access valid indicesi-1(which starts at1) andi.
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

