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

2 ビュー (過去 30 日間)
cpv008
cpv008 2018 年 11 月 28 日
回答済み: Rajanya 2025 年 3 月 19 日
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 Center および File ExchangeMathematics についてさらに検索

製品


リリース

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by