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

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

Risposte (1)

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.

Categorie

Prodotti

Release

R2017a

Richiesto:

il 28 Nov 2018

Risposto:

il 19 Mar 2025

Community Treasure Hunt

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

Start Hunting!

Translated by