How can I display the contents of a structure returned by my MATLAB Builder EX component in Excel?

1 view (last 30 days)
I have a MATLAB function that returns a structure. I have built this function into an Excel Add-in and I now wish to display the contents of the structure in an Excel worksheet.
My MATLAB function returnOutputStruct returns a structure with two fields, each of which contains a 24 x 1 double matrix. After importing the BAS file generated by the Builder EX, I select a 24 x 2 range of cells in my worksheet and call the function returnOutputStruct. When I do this, I get the following error
Error in VBAProject: Subscript out of Range

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 9 Nov 2009
You can work around this issue by using the MWStruct API. Since the MATLAB component returns a MWStruct, you can use the methods and properties of this class to extract the data of the structure into an VBA Array. As an example, you can edit the VBA code to read like:
Function returnOutputStruct(Optional in1 As Variant, Optional in2 As Variant) As Variant
Dim outStruct As Variant
On Error GoTo Handle_Error
Call InitModule
If outputStructureDemo Is Nothing Then
Set outputStructureDemo = CreateObject("StructureDemo.outputStructureDemo.1_0")
End If
Call outputStructureDemo.returnOutputStruct(1, outStruct, in1, in2)
'-----------------------Changes begin here----------------------------------
'Use the Item method to extract each field into a Variant
Dim col1 As Variant
Dim col2 As Variant
col1 = outStruct.Item(1, "field1")
col2 = outStruct.Item(1, "field2")
'Iterate through the fields to extract each element of each field into an Array
Dim outArray(1 To 24, 1 To 2)
Dim i As Integer
For i = 1 To 24
outArray(i, 1) = col1(i, 1)
outArray(i, 2) = col2(i, 1)
Next i
returnOutputStruct = outArray
'-----------------------Changes end here----------------------------------
Exit Function
Handle_Error:
returnOutputStruct = "Error in " & Err.Source & ": " & Err.Description
End Function

More Answers (0)

Categories

Find more on Excel Add-Ins in Help Center and File Exchange

Products


Release

R2009a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!