Main Content

Use Arrays with .NET Applications

Pass MATLAB Arrays to .NET

MATLAB® automatically converts arrays to .NET types, as described in the MATLAB Primitive Type Conversion Table. To pass an array of character arrays, create a cell array. For all other types, use the MATLAB NET.createArray function.

MATLAB creates a .NET array, copies the elements from the MATLAB array to the .NET array, and passes it to C#.

Convert Primitive .NET Arrays to MATLAB Arrays

To use a .NET array in MATLAB, call the appropriate MATLAB conversion function as shown in Convert Arrays of Primitive .NET Type to MATLAB Type. For example, suppose that a .NET method returns netArr of type System.Int32[]:

netArr = 
  Int32[] with properties:

            Length: 5
        LongLength: 5
              Rank: 1
          SyncRoot: [1×1 System.Int32[]]
        IsReadOnly: 0
       IsFixedSize: 1
    IsSynchronized: 0

Convert the array to a MATLAB array of int32.

B = int32(netArr)
B = 1×5 int32 row vector    
   1   2   3   4   5

Combine the elements in B with a MATLAB array.

A = int32([11 12 13 14 15]);
A + B
ans = 1×5 int32 row vector    
   12   14   16   18   20

Access .NET Array Elements in MATLAB

You access elements of a .NET array with subscripts, just like with MATLAB arrays.

You cannot refer to the elements of a multidimensional .NET array with a single subscript (linear indexing) like you can in MATLAB, as described in Array Indexing. You must specify the index for each dimension of the .NET array.

You can only use scalar indexing to access elements of a .NET array. The colon operator, described in Creating, Concatenating, and Expanding Matrices, is not supported.

Using the Get and Set Instance Functions

Alternatively, you can access elements of a .NET array using the Set and Get instance functions. When using Set or Get you must use C# array indexing, which is zero-based.

For example, create two System.String arrays, using the Set function and direct assignment:

d1 = NET.createArray('System.String',3);
d1.Set(0, 'one');
d1.Set(1, 'two');
d1.Set(2, 'three');

d2 = NET.createArray('System.String',3);
d2(1) = 'one';
d2(2) = 'two';
d2(3) = 'zero';

To compare the values of the first elements in each array, type:

System.String.Compare(d1(1),d2.Get(0))

MATLAB displays 0, meaning the strings are equal.

Convert .NET Jagged Arrays to MATLAB Arrays

You must convert a .NET jagged array before using it in a MATLAB command.

  • If the shape of the array is rectangular, use the corresponding MATLAB numeric function.

  • If the array is not rectangular, use the cell function.

If the jagged array is multidimensional, you must individually convert the arrays in each dimension.

See Also

|

Related Topics