Cookbook: Difference between revisions

Jump to navigation Jump to search
1,207 bytes added ,  1 February
 
Line 546: Line 546:
==== Problem ====
==== Problem ====


When using lsode or other ODE solver to find the state variables x as a function of time t in a set of ODE's, there seems to be no way to tabulate algebraic variables y that are a function of the state variables x and time t.
When using lsode or other ODE solver to find the state variables x as a function of time t in a set of ODE's, there seems to be no simple way to return and tabulate algebraic variables y that are a function of the state variables x and time t, other than the derivatives.
 
Consider a modified version of the spring function defined above in the section on parametric functions:
 
<syntaxhighlight lang="Octave">
function sprime=dspring (s, t)
  k=1;
  tau=1;
  x = s(1);
  v = s(2);
  y=x+v*tau;
  sprime(1) = v;
  sprime(2) = -k * y;
endfunction
</syntaxhighlight>
 
What would be a way to way to use this function and lsode to tabulate not just the elements of x and sprime, but also (say) y as a function of time?


==== Solution ====
==== Solution ====
UNDER CONSTRUCTION
 
Modify the function sprime to return y as a second argument:
 
<syntaxhighlight lang="Octave">
function [sprime,y]=dspring (s, t)
  k=1;
  tau=1;
  x = s(1);
  v = s(2);
  y=x+v*tau;
  sprime(1) = v;
  sprime(2) = -k * y;
endfunction
</syntaxhighlight>
 
lsode will happily ignore the second return argument y, but after x has been tabulated, y can be tabulated using the second return argument of the spring function in a for loop, e.g.
 
<syntaxhighlight lang="Octave">
t = linspace (0, 10, 100);
x = lsode ('dspring',[1;0], t);
y=zeros(length(t),1);
for i=1:length(t)
  [xtmp,y(i,1)]=dspring(x(i,:),t(i));
end
</syntaxhighlight>
 


==== Discussion ====
==== Discussion ====
UNDER CONSTRUCTION
 
This is a simple example with one algebraic variable. Others can be added by extending the second dimension of the y array.


[[Category:Examples]]
[[Category:Examples]]

Navigation menu