How to store a intermediate variable from ode45 function to the Workspace as a vector

30 views (last 30 days)
Having a system of two odes
I put the odes in a function and the script to solve the given function
I would like to store ALL "n" values in the Workspace. If I use "global n", I can see just one value of the n (the last one). Could you please help me to find a way for that case?
Thanks in advance
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function dx=funx1x2(t,x)
global n
S=250;
CC=2.35;
DD=0.65;
%State variables
k=x(1);
q=x(2);
L=k*S*CC;
D=q*S*DD;
n=sqrt(L^2+D^2)
%Equations of motion
dx=zeros(2,1);
dx(1)=q;
dx(2)=0.5*t*k;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Solver
clc; clear all;
global n
[t x]= ode45(@funx1x2,[0 5],[0 0.5]);

Accepted Answer

Jan
Jan on 22 Apr 2018
Edited: Jan on 22 Apr 2018

Remember that the ODE45 integrator has a stepsize controller, which can reject steps, if they are outside the error tolerance. Therefore storing the local positions inside the function to be integrated can reply invalid results. In addition the function to be integrated is called multiple times per step, such that you'd get more values of n than you get for the trajectory x. Afterwards it is not trivial to find out, which n belongs to which x.

Obtaining the values is much easier than with evil global variables which are known to cause more troubles than they solve:

function Main
  % clc; clear all;  % No, do not clear all
  [t, x]  = ode45(@funx1x2, [0 5], [0 0.5]);
  [dx, n] = funx1x2(t, x.');
  figure;
  subplot(1,2,1);
  plot(t, x);
  subplot(1,2,2);
  plot(t, n, 'c');
end
function [dx, n] = funx1x2(t, x)
  S  = 250;
  CC = 2.35;
  DD = 0.65;
  k  = x(1, :);
  q  = x(2, :);
  L  = k * S * CC;
  D  = q * S * DD;
  n  = sqrt(L .^ 2 + D .^ 2);
  dx = [q; 0.5 * t * k];
end

Now funx1x2 is "vectorized": I accepts the input x as vector. Then the integrator calculates the trajectory at first and n is created for the evaluated time points afterwards. The 2nd output n is inored during the integration.

Another option would be to use the outputfcn, which is called for the accepted steps only, but this is more complicated.

  2 Comments
Jan
Jan on 22 Apr 2018
[MOVED from section for answers:] Halil wrote:
First of all thank you so much for your help and detailed explanation. I applied the code which you explained above and now n is created as vector.
Jan
Jan on 17 Apr 2019
[MOVED from flags] Flagged by Changran He about 8 hours ago. ode save
@Cangran He: Please use flags only to inform admins an editors about inappropriate contents like spam or rudeness. Thanks.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!