MATLAB: How to use Excellink functions in a Excel Macro Function instead of a Sub

argumentbasiccelldeveloperexcelinMATLABmlputvarmoduleparameterpassvbavisualxlsm

I have a Macro Sub that passes in "A" and "b" named ranges to "myfunc" and returns the result to the "x" named range.
Sub Calculate()
MLOpen
MLPutMatrix "A", Range("A")
MLPutMatrix "b", Range("b")
MLEvalString "x = myfunc(A, bl)"
MLGetMatrix "x", "x"
MatlabRequest
End Sub
I can call this in Excel with "=Calculate()" and it populates "x", but now I want to call it like "=Calculate([rangeA], [rangeB])", where rangeA and rangeB can be any Excel range.
How can I do this with Excel Macro functions?

Best Answer

The above Macro Subroutine can be translated to the following Macro Function:
Function Calculate(A As Range, b As Range) As Variant
MLOpen
MLPutMatrix "A", A
MLPutMatrix "b", b
MLEvalString "x = myfunc(A, b)"
MLGetVar "x", Calculate
End Function
The inputs to MLPutMatrix are Ranges. MLGetVar is used to write the "x" from the MATLAB workspace to the "Calculate" variable.
Note Excel Macro Functions only support one output range. For MATLAB functions with multiple outputs, consider writing to multiple ranges directly.
MLGetMatrix "x", "x"
MLGetMatrix "y", "y"