Why am I receiving "Subscript indices must be real positive integers or logicals" error in my Euler's method code.

조회 수: 2 (최근 30일)
This is the code I am using to try to implement Euler's method and I keep receiving the above error at the 'f=' line. The function that is supposed to go there is this: y'(t) = t^-2(sin(2t)-2ty(t)). I have no experience with MatLab at all and have been fumbling my way through this whole course. Thanks for anybody who can help!
h = 0.25; % step size
t = 1:h:2; % the range of x
y = zeros(size(t)); % allocate the result y
y(1) = 2; % the initial y value
n = numel(y); % the number of y values
% The loop to solve the DE
for i=1:n-1
f=t.^-2*(sin(2*t)-2*t*y(t));
y(i+1)=y(i)+h*f;
end

답변 (1개)

Rajanya
Rajanya 2025년 3월 19일
The mentioned error is because of incorrect indexing of array 'y'. In MATLAB, all array indices must be logical or positive numeric integers.
Here in the code provided, 't' is a double array containing fractional(non-integral) numbers -
h = 0.25; % step size
t = 1:h:2; % the range of x
t
t = 1×5
1.0000 1.2500 1.5000 1.7500 2.0000
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
As a result, 'y(t)' in the following line throws the error since y(<non-integral index>) is not allowed.
f=t.^-2*(sin(2*t)-2*t*y(t));
Thanks.

카테고리

Help CenterFile Exchange에서 Mathematics에 대해 자세히 알아보기

제품


릴리스

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by