Pass mat file to matlab function block

조회 수: 5 (최근 30일)
Amjad MOUHAIDALI
Amjad MOUHAIDALI 2021년 10월 22일
답변: Pranjal Kaura 2021년 10월 26일
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개)

카테고리

Help CenterFile Exchange에서 Model, Block, and Port Callbacks에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by