Ever found yourself needing to tap into the power of a custom MATLAB function from within a Simulink model, specifically inside a MATLAB Function block? It's a common scenario, and thankfully, MATLAB offers ways to make this happen. The key often lies in how you tell Simulink that this external function isn't part of the standard, compiled code it expects.
One of the primary tools for this is coder.extrinsic(). Think of it as a signal to the code generator: "Hey, this function isn't something you can directly compile into the model; it needs to be called out to the MATLAB interpreter." This is crucial because Simulink, especially when preparing for code generation, likes to know the exact types and sizes of data it's dealing with. When you call a function that returns something called an mxArray – which is essentially a MATLAB data structure – and try to use it directly within an expression inside the MATLAB Function block, you'll hit a wall. The error message, "Found an mxArray. MxArrays are returned from calls to the MATLAB interpreter and are not supported inside expressions," is your clear indicator that the interpreter is involved.
The challenge, as one user pointed out, is when you don't know the exact dimensions of the data beforehand. This is where coder.varsize() comes into play. It's a way to declare that a variable can change in size, but you can set an upper bound. For instance, coder.varsize('y', [1024 2]); tells the system that the variable y will never exceed a size of 1024 rows and 2 columns. This provides enough information for the code generator to proceed, even if the actual size varies during runtime. You'd typically use it like this:
function y = myfun(x)
coder.varsize('y', [1024 2]); % Declare y as variable-sized with an upper bound
coder.extrinsic('fun'); % Declare 'fun' as an extrinsic function
y = zeros(x, 2); % Pre-declare type and size for clarity (optional but good practice)
y = fun(x); % Call the extrinsic function
end
However, it's worth noting that sometimes, especially in older versions of MATLAB (like 2019b mentioned in a discussion), the callback for coder.varsize() within Simulink might not be directly supported. This can lead to further troubleshooting. The core idea remains: you need to provide the necessary hints to Simulink about how to handle these external calls and potentially variable data sizes.
So, when you're looking to call a function from a specific directory within a MATLAB Function block, remember coder.extrinsic() is your first step. If you're wrestling with unknown variable sizes, coder.varsize() is your next best friend, offering a way to define boundaries and keep the code generation process moving forward. It's all about giving Simulink the right context to understand and integrate your custom MATLAB logic.
