How do I pass an array of strings from C# to MATLAB using MATLAB Builder NE 3.0.2 (R2009b)?

조회 수: 3 (최근 30일)
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.

채택된 답변

MathWorks Support Team
MathWorks Support Team 2012년 10월 30일
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)
{
MWCellArray inputString = null;
MWCharArray resultString = null;
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);
resultString = (MWCharArray)demo.concatStringArrays(inputString);
Console.WriteLine("resulting string from MATLAB function is {0}", resultString);
Console.ReadKey();
}
catch (Exception exception)
{
Console.WriteLine("Error: {0}", exception);
Console.ReadKey();
}
}
}
}

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Deploy to .NET Applications Using MWArray API에 대해 자세히 알아보기

제품


릴리스

R2009b

Community Treasure Hunt

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

Start Hunting!

Translated by