I get "index must be a positive integer or logical. " Error, please help
조회 수: 1 (최근 30일)
이전 댓글 표시
Hello, I write a code that use third-order Runge Kutta method. I want my result in tabulated form which i starting with 0, ti, yi (represents numerically estimated value), yei(true value) and et ( true percent absolute relative error).
Finally, I want to plot the true solution together with the numerical solution in the same place.
I have dy/dt = t*e^(3*t)-2*y , step size 0.1 , the true solution ye(t) = 1/5*t*e^(3*t)-(1/25)*e^(3*t)+(1/25)*e^(-2*t)
I write a code but when I run that, I get
i ti yi yei |Et|
Attempted to access t(0); index must be a positive integer or logical.
Error in hw5 (line 22)
k1(i)=f(t(i),y(i));
>>
MY i HAS TO BE START WITH 0.
HOW CAN I SOLVE THAT? THANKS
clc
clear all
close all
fprintf('%10s %10s %10s %10s %10s\n','i','ti','yi','yei','|Et|')
h=0.1; %initial step size
t=0:h:1; %time array with initial step size
c=length(t); %number of time values with 0.1 step size
y=zeros(1,c); %creating an empty array for numerically calculated 'y' values
%y(0)=0 in this definition. so, initial value is already included.
y_2=zeros(1,c); %creating an empty array for numerically calculated 'y' values
y_true=zeros(1,c); %creating an empty array for exact 'y' values
E=zeros(1,c); %creating an empty array for estimating local truncation errors
%defining the ODE, f = dy/dt
f = @(t,y) t*exp(3*t) - 2*y;
%% Part a
klmn=zeros(1,c-1);
for i=0:1:(c-1)
%defining k1,k2 and k3 for each case
k1(i)=f(t(i),y(i));
k2(i)=f((t(i)+h/2),(y(i)+h/2*k1(i)));
k3(i)=f((t(i)+h/2),(y(i)+h/2*k2(i)));
%defining next value of dy/dt, y(i+1) numerically
y(i+1)=y(i)+(h/6)*(k1(i)+2*k2(i)+2*k3(i));
%real value of y(i+1)
y_true(i+1)=1/5*t(i+1)*exp(3*t(i+1))-(1/25)*exp(3*t(i+1))+(1/25)*exp(-2*t(i+1));
%true error calculation
et(i+1)=abs(y(i+1)-y_true(i+1))./y_true(i+1);
fprintf('%10s %10s %10s %10s %10s\n',i,t,y,y_true,et)
end
댓글 수: 0
답변 (1개)
dpb
2019년 5월 27일
편집: dpb
2019년 5월 27일
"MATLAB is not C"
...
for i=0:1:(c-1)
%defining k1,k2 and k3 for each case
k1(i)=f(t(i),y(i));
...
Matlab arrays are one-based, not 0-based. Write
for i=1:c
%defining k1,k2 and k3 for each case
k1(i)=f(t(i),y(i));
...
instead (and fix up any other references that assume 0-based arrays as well, of course).
댓글 수: 2
dpb
2019년 5월 28일
The first fprintf is before any variables are defined.
You still have an indexing issue when i==c, i+1 will be outside array boundaries.
Other than that, nothing terribly obvious in "just looking"; use the debugger and step through your code looking for logical issues...
참고 항목
카테고리
Help Center 및 File Exchange에서 Ordinary Differential Equations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!