why am i getting the error: Index in p

2 views (last 30 days)
WILLIAM Sherman
WILLIAM Sherman on 10 Oct 2018
Edited: Star Strider on 10 Oct 2018
why am I getting the error: Index in position 1 is invalid. Array indices must be positive integers or logical values. Here is my code,
function [t, y] = myeuler(f, tinit, yinit, h, n)
t = zeros(n+1, 1);
y = zeros(n+1, 1);
t(1) = tinit;
y(1) = yinit;
for i = 1:n
t(i+1) = t(i) + h;
y(i+1) = y(i) + h*f(t(i), y(i));
end
  2 Comments
the cyclist
the cyclist on 10 Oct 2018
Can you please provide an simple example of the inputs you call this function with, that gives the error?
WILLIAM Sherman
WILLIAM Sherman on 10 Oct 2018
Edited: the cyclist on 10 Oct 2018
sure, I put in
f=(-3*y/t)+9*t.^2
tinit=-.5
yinit= 3.15
h= .2
n=10

Sign in to comment.

Answers (2)

the cyclist
the cyclist on 10 Oct 2018
Calling your function like this worked for me:
f = @(t,y)(-3*y/t)+9*t.^2;
tinit=-.5;
yinit= 3.15;
h= .2;
n=10;
[t,y] = myeuler(f,tinit,yinit,h,n)

Star Strider
Star Strider on 10 Oct 2018
Edited: Star Strider on 10 Oct 2018
You may be calling ‘myeuler’ incorrectly. You must pass your ‘f’ argument as a function handle:
[t, y] = myeuler(@fcn, tinit, yinit, h, n)
This assumes that all the other arguments have been defined, and that your function name is ‘fcn’, and that ‘fcn’ is a function file.
If it is an anonymous function in your workspace, it already exists as a function handle, and you would call it as:
[t, y] = myeuler(fcn, tinit, yinit, h, n)
EDIT (10 Oct 2018 at 20:18)
Note that ‘f’ has to be a function, and the usual format for the MATLAB ODE solvers is for the first argument to be the independent variable, and the second argument the independent variable. The output is a column vector of the derivatives.
That also appears to be what ‘myeuler’ expects.

Categories

Find more on MATLAB in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!