MATLAB ode45 OutputFcn to monitor changing value of if loop

598 views Asked by At

I try to save/see my variable m that is changed by an if loop during an ode45 differential equation solving process.

%Some parameter setting above
myfun=fprintf('m', num2str(m))
options = odeset('NonNegative',[1:3],'RelTol',1e-5,'AbsTol',1e-8, 'OutputFcn', @myfun);
[t,x] = ode45('myfunction', tspan, x0, options); %calculation

the if loop is in the equation file before all the other equations follows:

if x(1)>=threshold
    m=1 ;
   return
else
    m=0 ;
end

I already took a look at the matlab description for the OutputFcn Option for ode45 and also read https://de.mathworks.com/help/deeplearning/ug/customize-output-during-deep-learning-training.html without understanding it properly. I am also open to other solutions to "see" which value m during the ode calculation has.

1

There are 1 answers

1
rinkert On BEST ANSWER

Create a separate file, and call this myOutputFcn.m, with the following code

function status = myOutputFcn(t,y,flag,threshold)

    switch(flag)
        case 'init' % code to run before integration
            ;
        case ''     % code to run after each integration step
            % act on state
            if y(1)>=threshold
                m = 1;
            else
                m = 0;
            end
            % print m 
            fprintf('% 4.3f\t%i, t, m\n',t,m);
        case 'done' % code to run when integation is finished
            ;
    end

    status = 0; % need to set status, otherwise integration will halt

end

Then to call this output function every iteration with the right threshold, you will have to do the following

threshold = 10; % idk, your threshold
options = odeset('NonNegative',[1:3],'RelTol',1e-5,'AbsTol',1e-8, 'OutputFcn', @(t,y,flag) myOutputFcn(t,y,flag,threshold));
[t,x] = ode45('myfunction', tspan, x0, options); %calculation