Why am I receiving "Subscript indices must be real positive integers or logicals" error in my Euler's method code.
11 views (last 30 days)
Show older comments
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
0 Comments
Answers (1)
Rajanya
on 19 Mar 2025
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
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));
You can also refer to a similar question for more insight - https://www.mathworks.com/matlabcentral/answers/423701-subscript-indices-must-either-be-real-positive-integers-or-logicals.
Thanks.
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!