필터 지우기
필터 지우기

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

조회 수: 9 (최근 30일)
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]);

채택된 답변

Jan
Jan 2018년 4월 22일
편집: Jan 2018년 4월 22일

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
Jan
Jan 2018년 4월 22일
[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 2019년 4월 17일
[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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by