MATLAB: Do I get a run-time error when importing matrix from MATLAB to Excel

linkspreadsheetSpreadsheet Linkworkbook

I am using GetFullMatrix function in my VBA code to import a matrix from MATLAB to Excel. Here is my code
Dim MatLab As Object
Dim Result As String
Dim A_real(4,3) As Double
Dim A_imaginary(4,3) As Double
Set MatLab = CreateObject("matlab.application")
Result = MatLab.Execute("M=rand(4,3)")
Call MatLab.GetFullMatrix("M", "base", A_real, A_imaginary)
MatLab.Quit
However, I get the following runtime error in Excel
RUN-TIME ERROR '-2147352567 (80020009)' Exception occurred.

Best Answer

This automation error indicates that an error occured in MATLAB running as server application. The run-time error in this case is caused due to wrong indexing of matrices. In MATLAB, matrices are index '1' based and in Excel they are index '0' based. Hence, for any given matrix 'X', MATLAB indexes the first element as X(1,1), whereas Excel indexes the same element as X(0,0).
If you want to retrieve a 'm x n' matrix in Excel, ensure that the corresponding MATLAB matrix is 'm+1 x n+1'.
To resolve this error, use the following VBA code instead
Dim MatLab As Object
Dim Result As String
Dim A_real(4,3) As Double
Dim A_imaginary(4,3) As Double
Set MatLab = CreateObject("matlab.application")
Result = MatLab.Execute("M=rand(5,4)")
Call MatLab.GetFullMatrix("M", "base", A_real, A_imaginary)
MatLab.Quit
Set MatLab = Nothing