MATLAB: How to convert an MWArray returned by the MATLAB Builder NE component to a native .NET array in Visual Basic

castMATLAB Builder NEtype

I have compiled an MATLAB file into a .NET component using MATLAB Builder NE. The MATLAB file returns multiple output arguments of mixed type; for example:
function [argout1, argout2, ..., varargout] = foo(argin1, argin2, ...., varargin)
When I try cast one of the output MWArray arguments to a native .NET array using the ToArray() method, I get the following error in Visual Studio:
'ToArray' is not a member of 'MathWorks.MATLAB.NET.Arrays.MWArray'.
I would like to be able to cast each individual output argument stored in the MWArray into a native .NET array as I see fit.

Best Answer

ToArray() is a method that is valid only for the MWNumericArray, MWLogicalArray, and MWCharArray types. An element of an MWArray object must be cast to one of these types first before a ToArray() may be issued.
Use the CTYPE Visual Basic function to cast each element of the MWArray array into an MWNumericArray, MWLogicalArray, or MWCharArray, and then call ToArray() on the result. For example, if 'foo' is the MWArray object that contains the various output arguments, the following statement converts the first output argument into a native .NET Double array by way of the MWNumericArray type:
Dim nativeArray(,) As Double = CType(foo(1), MWNumericArray).ToArray(MWArrayComponent.Real)
Refer to the MATLAB Builder NE MWArray Class Library Reference for more details: