# Not sure why vector changes assignment when using ode45

1 view (last 30 days)
3816R on 30 Nov 2019
Commented: Steven Lord on 1 Dec 2019
I am going to simplify the problem out of context as I believe this will be easier to understand, obviously I will be corrected if this is actually unhelpful.
There's 3 m files. Main, secondfun, thirdfun.
In main I have defined an 8 element vector i.e.
vector=[var1 var2 var3 var4 var5 var6 var7 var8]
In main I then call the second function with vector as one of the inputs i.e.
[out1, out2]=secondfun(in1, in2, in3, vector)
Where secondfun m file has secondfun(x,y,z,vector):
y0=[vector(1);vector(2);vector(3)]
[~,out3]=ode45(@thirdfun,t,y0,vector)
and thirdfun, thirdfun(~,vector) has:
out3=zeros(3,1);
out3(1)=(vector(5)-vector(1))/vector(7); *****
out3(2)=(vector(5)-vector(2))/vector(8);
out3(3)=(vector(4)-vector(3))/vector(6);
So running this I get the error that on the second line in thirdfun: Index exceeds matrix dimensions.
I narrowed this error down to where I'm using ode45 in secondfun. Before that line the vector function is a 8 element row vector as it should be. After that line it's turned into y0 only (3 element column vector), i.e. it's being passed into secondfun fine as far as I understand but I don't understand where or how it's being redefined as that?
Any advice on this would be much appreciated.
Thanks.

Steven Lord on 30 Nov 2019
[~,out3]=ode45(@thirdfun,t,y0,vector)
This isn't the right way to pass a third input (beyond the two that ode45 passes into the integrand function automatically) into thirdfun, which is what I assume is your intention. Instead vector is being interpreted as the options input to ode45.
There's an example on the ode45 documentation page showing one technique for passing additional parameters into the integrand function and a link (in the description of the odefun input on the documentation page) that describes a few other techniques.
Steven Lord on 1 Dec 2019
That call would work if the only thing thirdfun accepted was the vector. In this case, the anonymous function works like an adapter. ode45 requires the function you pass into it as the first input to accept two inputs, the vector of times and the vector of state values. thirdfun requires the function that calls it to pass in (I'm guessing) the vector of state values and the vector of additional parameters. The anonymous function:
@(t, y) thirdfun(y, vector)
could be called by ode45 with two inputs (as it requires) and calls thirdfun with two inputs (as it requires.) It ignores the information ode45 passed in that thirdfun doesn't need and provides extra information to thirdfun above and beyond what ode45 gave it.

Jim Riggs on 30 Nov 2019
I dont think that the statement
out3=(3,1)
is a valid statement. It may be that out3 is not the size that you intend.
try
out3 = zeros(3,1);
3816R on 30 Nov 2019
this wasn't the answer - I already had the zeros in my code. The issue is seemingly with ode45.