How do I pass an array of strings from C# to MATLAB using MATLAB Builder NE 3.0.2 (R2009b)?
Problem Description:
I have created a .NET component using MATLAB Builder NE product. I would like to pass an array of string from C# program to the MATLAB function in the .NET component.
Solution:
It is possible to create a string array in C# and pass it to an MWCharArray like below:
String[] input = new String[2] {"This", "is"}; MWCharArray inputStr = new MWCharArray(input);
But unfortunately, MWCharArray sends the array of strings to MATLAB as a column vector but not as a row vector. Thus it is not very useful when we send array of strings in the above way.
So the best way to send array of strings from C# to MATLAB is by creating an MWCellArray. Please see below for a complete example on how to pass array of strings from C# to MATLAB:
Here is simple MATLAB code which takes input as a cell array and concatenates the contents of cell array with other strings:
function result = concatStringArrays(input) strVar = ['a', 'concatenated', 'string']; result = [input{1}, input{2}, strVar]; end
Please note that Matlab array starts at index 1 instead of 0 unlike in C#
After creating the .NET component from the above MATLAB code, the component can be used in the C# .NET application like below:
using System; using System.Collections.Generic; using System.Text;
using MathWorks.MATLAB.NET.Utility; using MathWorks.MATLAB.NET.Arrays;
using stringArray;
namespace StringArr { class Program { static void Main(string[] args) {
try { StringArray demo = new StringArray(); inputString = new MWCellArray(2); inputString[1] = new MWCharArray("This"); inputString[2] = new MWCharArray("is");
Console.WriteLine("String input converted to pass to MATLAB .NET component is\n{0}", inputString);