Array indices must be positive integers or logical values. Midpoint Method help

1 次查看(过去 30 天)
clc
clear all
close all
tic
h = 0.25 ; % Step size = 0.25
t = 0:h:2; % the range of x from 0 to 2 with a step size 0.25
y = zeros(1,length(t)); % matrix for allocate the y values
y_a = 2.02974 * 10^65; % analytical value at x=2
y(0) = 0 ; % initial value
n = numel(y);
func = @(x,y) (-200000 .* y + 200000 .* exp(-x) - exp(-x)); % the derivative function
for i=1:n-1
k_1 = func(t(i),y(i)); % to call the derivative function for k1
k_2 = func(t(i)+0.5.*h,y(i)+0.5.*h.*k_1); % to call the derivative function for k2
y(i+1) = y(i) + (h.*k_2);
end
E = (abs(y_a-y)/y_a)*100; %Relative error at x=2
toc
I try to solve the func equation with initial condition y(0)=0 but MATLAB gives me error which is
Array indices must be positive integers or logical values.
Error in Midpoint (line 10)
y(0) = 0 ; % initial value
Can you help asap?

采纳的回答

Jonas
Jonas 2022-5-3
编辑:Jonas 2022-5-3
matlab's indexing starts with 1 and not with 0, the first element of y is y(1). maybe you wanted to write y(t==0)=0, which is the same as y(1)=0 here

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by