MATLAB: How to use the GetFullMatrix method to get a dynamic MATLAB matrix into Visual Basic

arraysdimensiondynamicgetfullmatrixMATLABMATLAB Compilerunknow

How do I use the GetFullMatrix method to get a dynamic MATLAB matrix into Visual Basic?
From the examples in the MATLAB External Interfaces manual related to using MATLAB as an Active X Automation Server, it appears that the VB Automation Client must know the dimensions of a matrix in the MATLAB workspace prior to accessing it with the 'GetFullMatrix' method.
In the examples in the manual, the VB code uses fixed array dimensions to access MATLAB matrices. If the dimensions of a MATLAB matrix change dynamically, then the VB arrays required a Redim( , ) statement prior to the getfullmatrix call in order to prevent any errors. I also tried to use Variant data types for the VB arrays, but received type mismatch errors in getfullmatrix call. Is there any way of declaring array types in VB that can access a MATLAB matrix with unknown dimension?

Best Answer

One way of doing this is to declare a dynamic array in Visual Basic and then redimension the array to determine the size of the MATLAB matrix with an initial call to MATLAB using GetFullMatrix.
Then the output from this call to GetFullMatrix can be used to redimension the Visual Basic array using the ReDim keyword.
The following code illustrates how to do this:
Dim MatLab As Object
Dim Result As String
Dim Mrsize(1 To 2) As Double
Dim Misize() As Double
Dim MReal() As Double
Dim MImag() As Double
Dim i, j As Integer
Private Sub Command1_Click()
Set MatLab = CreateObject("Matlab.Application")
Result = MatLab.Execute("surf(peaks)")
Call MatLab.Execute("B2 = round(100*rand(1+round(10*rand)))")
Call MatLab.Execute("[r,c] = size(B2); B2_size = [r, c];")
Call MatLab.GetFullMatrix("B2_size", "base", Mrsize, Misize)
ReDim MReal(1 To Mrsize(1), 1 To Mrsize(2))
Call MatLab.GetFullMatrix("B2", "base", MReal, MImag)
For i = 1 To Mrsize(1)
For j = 1 To Mrsize(2)
RealValue = MReal(i, j)
Next j
Next i
End Sub