How to use cfit objects in Simulink?
32 views (last 30 days)
I want to use a cfit object (obteined from Curve Fitting Tool) in a Simulink application. For this I use the follow MATLAB Function block ("myBat") in Simulink :
function y = myBat(u)
y2 = evalin('base','f');
y = feval(y2,u);
Where "f" is the cfit object in Matlab Workspace. However in the simulation appears the next error message:
MATLAB expression 'evalin' is not numeric.
I guess this error apears because the variable "y2" isn´t declare or inicialliting correctly.
Thanks for your help.
PD. Sorry for the english.
Andy Bartlett on 5 Jan 2022
Edited: Andy Bartlett on 2 Feb 2022
The attached model and MATLAB code show how a fit created with Curve Fitting Toolbox can be called from a MATLAB Function Block and also used with MATLAB Coder to create a mex file.
Create a "lean" wrapper function to be called via coder.extrinsic. Try to create a function signature that just takes in numeric (or logical) data and outputs numeric (or logical) data. See callFit1.m
Break the problem into two steps. First, get the function working with MATLAB Coder codegen command. Deal with MATLAB Function Block needs only after you've made codegen happy. See test_callFit1FromCoder.m and callFit1FromCoder.m
For the MATLAB Function Block, use a very thin wrapper that calls what you got working with codegen in recommendation 2. See ex_MATLAB_Function_Block_call_curve_fit_R2018a.slx.
You are likely to see additional errors due to the additional constraints of use in a MATLAB Function block.
You'll need to learn and use additional "tricks of the trade" to keep MATLAB Function Block happy such as the "colon assignment trick." See the comments in callFit1FromCoder.m.
As you make changes to your MATLAB code, be sure to test both codegen by itself and MATLAB Function Block. So for this example, you'd first rerun test_callFit1FromCoder.m and then simulate the model ex_MATLAB_Function_Block_call_curve_fit_R2018a.slx. If both are happy, then you've succeeded.
I tested the attachments in R2020b. I fully expect this to work in newer release too.
I expect, but can't promise, the MATLAB code should work for releases mutliple years back.
I exported the Simulink model to R2018a. My hope is it will work in R2018a and newer. But, I didn't test that, so no promises.
R2016a Updated Note
Sorry didn't realize the original need was for R2016a. I exported the model to prior release as
I loaded this in R2016a and clicked the sim button, it worked fine.