필터 지우기
필터 지우기

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
  댓글 수: 2
Muzaffer Cagislar
Muzaffer Cagislar 2022년 5월 3일
so you mean that y(1) will be equal to actually x=0 right?
Torsten
Torsten 2022년 5월 3일
편집: Torsten 2022년 5월 3일
Your analytical solution is totally wrong.
y_a(x) = exp(-x)-exp(-200000*x)
which gives
y_a(2) = exp(-2)-exp(-400000)

댓글을 달려면 로그인하십시오.

추가 답변 (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