How do I use ODE45 in a Matlab System block with code generation?
Show older comments
I'm trying to write a matlab.System that integrates an ODE using ODE45 in its discrete step function. This system should then be used in a Simulink Matlab System block with code generation enabled (no way to get around that since it needs to run on a real time system). All of this is happening using Matlab R2015b, also no way to get around that.
Here is a simple system that demonstrates my problem:
classdef ODESystem < matlab.System & matlab.system.mixin.Propagates
properties (DiscreteState)
x
end
methods (Access = protected)
function y = stepImpl(obj, u)
h = 0.1; % step width
[~, xs] = ode45(@(t_, x_) ODESystem.sys_f(x_, u), [0, h/2, h], obj.x);
obj.x = xs(end); % new state at t+h
y = ODESystem.sys_h(obj.x); % output function
end
function resetImpl(obj)
obj.x = 0;
end
% also a bunch of signal property definition functions, can be seen in the attachment
end
methods (Static)
function dx = sys_f(x, u)
dx = u - x;
end
function y = sys_h(x)
y = x^2;
end
end
end
And what it looks like in Simulink:

All of this works when running in interpreted mode. Code generation fails however, because anonymous functions are not supported yet in R2015b. So my question is:
How do I parameterize the ODE function with the current input u without using anonymous functions?
Workarounds that I tried and failed: nested functions, storing the current value u in a global variable, a persistent variable, a class property (can't pass a handle to an object method). All of these are not supported for Matlab System objects in Simulink Matlab System blocks.
1 Comment
Robert Heedt
on 21 Jul 2019
Answers (0)
Categories
Find more on Create System Objects 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!