MATLAB: How to invoke the custom MATLAB function using Spreadsheet Link EX

customexfunctionlinkMATLABspreadsheetSpreadsheet Link

I would like to call a MATLAB function that I have written, directly from an Excel cell, without writing any VBA macro.

Best Answer

To call your MATLAB function from an Excel cell using Spreadsheet Link EX API, follow these steps:
1. Write your MATLAB function. For example, 'myMLFcn.m'.
2. Move your MATLAB function to one of the directories in MATLAB startup path or, add a command to one of MATLAB startup files to include your directory at startup. For example, add the following to the end of MATLABRC.M:
addpath '$MATLAB_FUNCTION_ROOT'
where $MATLAB_FUNCTION_ROOT is the directory containing your MATLAB function. This will ensure that whenever you start MATLAB, either in full desktop mode or as a COM automation server, your function will be visible.
3. If required, export the data from your spreadsheet to MATLAB using MLPutMatrix or equivalent APIs.
4. Invoke your MATLAB function 'myMLFcn' as:
=MLEvalString("[y1, y2, ...] = myMLFcn(x1, x2, ...)")
where y1, y2, ...are output arguments and x1, x2, ...are input arguments. Note that the command as invoked here assumes that x1, x2, ...already exist in MATLAB workspace.
5. If required, bring the output arguments back to the spreadsheet using MLGetMatrix or equivalent APIs.