Pass mat file to matlab function block

5 次查看(过去 30 天)
Dear community,
I created a subsystem with a mask to enter the name of a mat file (figure below).
In my subsystem, i have a matlab function (figure below)
The code in the matlab function is as follows:
function y = fcn(fname,u)
x = load(fname);
y = x.factor *u;
The simulation files are attached.
I used the string constant to pass the file name to the matlab function, but it not working.
I want my subsystem to be protected, so the user can't access the matlab function. The user can only provides the mat file name.
The main question is how to pass a mat file to matlab function block throw a mask. The real model is more complicated, this is just a simple demonstration.
Thank you, Amjad


Pranjal Kaura
Pranjal Kaura 2021-10-26
Hey Amjad,
The issue in your model is that the custom code written inside the MATLAB function block, is not supported for code-generation. This is because you're using structures inside the MATLAB Function block, and structs have limited capability while being used inside code generatable functions (you can read more about it here and here).
Thus when you use variable sized 'fname' inside your MATLAB Function block, which in turn calls 'load' and assigns the 'load' output to another struct named 'x', MATLAB throws an error because 'fname' is a 'non-constant expression'.
A workaround could be to use Dynamic Mask Callbacks and add a callback to the 'fileName' parameter, so that whenever the user modifies the 'fileName' param, the callback is called.
You can then add the custom code in the callback.
e.g. for the attached model, you could write this code in the callback
fileName = get_param(gcb,'File_to_Load');
x = load(fileName);
set_param(gcb, 'f', num2str(x.factor));
Wherein 'f' is another parameter in the subsystem mask which you can then pass to your MATLAB Function block.
I have attached the modified Simulink model for your reference.
You can refer to the following link to learn more about callbacks:
Hope this helps!

更多回答(0 个)




Community Treasure Hunt

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

Start Hunting!

Translated by