How do I use ODE45 in a Matlab System block with code generation?

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 comentario

I found a workaround: Don't use the "MATLAB System" block in Simulink. Instead use a "MATLAB Function" block. In the functions code I manually instantiate the matlab.System object, store it in a persistent variable and call the setup, step, ... methods. Code generation works this way for some reason.

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Más información sobre Create System Objects en Centro de ayuda y File Exchange.

Productos

Versión

R2015b

Preguntada:

el 11 de Jul. de 2019

Comentada:

el 21 de Jul. de 2019

Community Treasure Hunt

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

Start Hunting!

Translated by