Using a function_handle 'variable' from workspace in simulink

I have a script where I define a function as e.g.
f = @(x) 16*sin(3*x).*exp(-x.^2)+atan(x+1);
Here f is now a function handle (function_handle) in the workspace. With this script I have a corresponding simulink model where I simulate a dynamical system which has this function somewhere incorporated.
Right now, I either copy this function in a Fcn or MATLAB function block, or parametrize it such that I have the structure (k1*sin(k2*x).*exp( ...etc.)) hardcoded in the simulink model and I can change 16 easily to 12 without opening the simulink model. However, I want to change the whole function without opening the simulink model (just as changing the value of a constant).
I have no idea to do this, do you have any suggestions?
Note: I'm a student, i'm using 2020a and have access to all possible toolboxes

 Accepted Answer

function handle is not supported by Simulink. Run "showblockdatatypetable"
"I want to change the whole function without opening the simulink model". There migth be a stratch way to do it. Have a MATLAB Function block, which calls a function defined in a saved .m file. In the saved .m file, call a function handle "f" defined in the base workspace. When you have this set up, you might be able to change the function handle in base workspace, and then run Simulink simulation.

3 Comments

Dear Fangjun,
Thanks for the solution. It did not work totally as you meant but it made me think about the following solution:
In the .m file have the following:
% define function
f = @(x) 16*sin(3*x).*exp(-x.^2)+atan(x+1);
% make symbolic expression
fsym = f(sym('x'));
% generate a .m function file named 'getNonlinearity' that contains the function f
matlabFunction(fsym,'File','getNonlinearity');
The generated function now contains:
function out1 = getNonlinearity(x)
%GETNONLINEARITY
% OUT1 = GETNONLINEARITY(X)
% This function was generated by the Symbolic Math Toolbox version 8.5.
% 13-Aug-2020 10:29:17
out1 = atan(x+1.0)+sin(x.*3.0).*exp(-x.^2).*1.6e+1;
And this function I can call in the simulink model with a "MATLAB Function" block!
function y = nonlinearity(u)
y = getNonlinearity(u);
And then it is possible to run. You of course need the symbolic toolbox for this...
Thank you for the follow up comments. I learned something new from this today.
do u have idea how i can do in the case of trained neural ode?

Sign in to comment.

More Answers (0)

Categories

Find more on General Applications in Help Center and File Exchange

Products

Release

R2020a

Community Treasure Hunt

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

Start Hunting!