MATLAB: Do I receive Undefined function errors for HEAVISIDE function when I try to compile it in a FIT object in MATLAB 7.8 (R2009a)

MATLAB Compiler

I am computing a FIT using the HEAVISIDE function. This works fine inside MATLAB but fails with the following error in my compiled application.
??? Error using ==> fittype.fittype>fittype.fittype at 466
Expression a.*heaviside(b-x).*(b-x) is not a valid MATLAB expression,
has non-scalar coefficients, or cannot be evaluated:
Error in fittype expression ==> a.*heaviside(b-x).*(b-x)
??? Undefined function or method 'heaviside' for input arguments of type
'double'.

Best Answer

The HEAVISIDE function is a function present in the Symbolic Math Toolbox. The Symbolic Math Toolbox functions cannot be compiled using the MATLAB Compiler.
To workaround this issue, you can write your own heaviside function as shown below:
function Y = heaviside1(X)
%HEAVISIDE Step function.
Y = zeros(size(X));
Y(X > 0) = 1;
Y(X == 0) = .5;
end
Now, you can use the above custom heaviside function in your MATLAB code as follows:
function my_fit
% Create a fit
x = [1:10]';
y = x*0.25;
z = [-0.5:0.1:0.5];
% Create a FIT
cfit = fit(x,y,'a.*heaviside1(b-x).*(b-x)'); % using custom heaviside1
cfit
d = cfit(z);
plot(x,y,'*k',z,d,'.');
You can then compile this code into a standalone executable using the following command:
mcc -m my_fit.m -a heaviside1.m