0

I have a function func() definition which contains a for() cycle.

Can I then pass func() to lsode() to be resolved as an ODE?

Update: Example of the code.

int = [0; 0];
slp = [0; 1];
x = [1:10];
r = zeros(1,10);
for id = 1 : 2;
 r = r + int(id) + slp(id)*x;
end
plot(x,r);
function ydot = fnc(y, t, int, slp)
 ydot = zeros(1,10);
 for jd = 1 : 2;
  ydot = ydot + int(jd) + slp(jd)*t;
 end
end
p = lsode(@(y,t) fnc(y,t,int,slp), 1, x);

error: lsode: inconsistent sizes for state and derivative vectors error: called from: error: /path$/test_for_function.m at line 15, column 3

Fabio Capezzuoli
  • 599
  • 7
  • 23
  • 1
    Then debug your program and determine the shape of the state and derivative vectors, in the main if they are row or column vectors. Both should be the same. You could add a print statement in `fnc` for the shape of `y` and `ydot`. – Lutz Lehmann Mar 17 '18 at 15:06
  • Did you want to pass `r` as initial value? That should be `p = lsode(@(y,t) fnc(y,t,int,slp), r, x);`. Does the error change with that correction? – Lutz Lehmann Mar 17 '18 at 15:17

2 Answers2

1

The error message has nothing to do with the computations inside the ODE functions. It is telling you that the shape of ydot is incompatible with the shape of the state vector that is established by the initial value vector.

First I can not identify in your code example the initial value vector. You seem to construct the array r for that, but you pass the scalar constant 1.

And then it could be as simple as switching the shape dimensions in the construction of ydot. Or use ỳdot = zeros_like(y) or similar if available.

Lutz Lehmann
  • 25,219
  • 2
  • 22
  • 51
0

After some debugging, tinkering and thinking about how lsode works, I found how to make my code work as intended:

%Start code
int = [0; 0];
slp = [0; 1];
x = [1:10];
for id = 1 : 2;
 r = int(id) + slp(id)*x;
end   %A complicated way to draw a line
 figure(1); clf(1); 
 plot(x,r);
 hold on;
function ydot = fnc(y, t, int, slp)
 for jd = 1 : 2;
  ydot = [int(jd) + slp(jd)*t];
 end
end
p = lsode(@(y,t) fnc(y,t,int,slp), 1, x);
 plot(x, p, '-r');
%EOF

And the result is: enter image description here

As it should be.

Fabio Capezzuoli
  • 599
  • 7
  • 23