Can I put an anonymous function into a Simulink block

16 views (last 30 days)
Although pretty good with Matlab, I’m a total amateur with Simulink so hoping someone can help.
I have a Matlab function y = fun1(x,M) that I want to put into a Simulink block (and later create an S-function version). x will come from another block in the Simulink model. M is a structure with a lot of information; it doesn’t change and I want to embed it in the Simulink block. I don’t want the block to have to load M from a matfile or call additional functions each time.
So, I thought to create an anonymous function as follows: anon_fun = @(x)fun1(x,M);
And then put the anon_fun in a Matlab Function, fcn or similar Simulink block. But none of these seem to work!
Is it possible to embed an anonymous function in a Simulink block, which type, and will I be able to generate an S-function from it?
Thanks in advance for any tips.

Accepted Answer

Mandar Patwardhan
Mandar Patwardhan on 22 Dec 2016
If your use case is to create S-function, then refer to the following link which discusses the detailed steps to create a Level 2 MATLAB S-function. https://www.mathworks.com/help/simulink/sfg/writing-level-2-matlab-s-functions.html#brgtux6
You can create an S-function block, as shown in the example, add it in your model and provide a signal representing x as an input to this block.
If you do not intend to change the structure represented by M, then you can use a persistent variable and directly use it inside an S-function. There is no need to pass M as a parameter in that case because you will always have access to M inside the function. For information regarding persistent variables refer to the following link. https://www.mathworks.com/help/matlab/ref/persistent.html Additionally, it is not clear why would you use Anonymous functions inside a MATLAB function block. The use case which you are discussing can be definitely achievable using a Level-2 MATLAB S-function.

More Answers (0)

Categories

Find more on Simulink Functions in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!