如何将一个C#字符串数组传递给MATLAB

本文详细介绍了如何通过MATLABBuilderNE产品将C#中的字符串数组传递至MATLAB,并提供了实例代码演示,包括创建字符串数组、转换为特定MATLAB格式以及调用MATLAB函数处理数组内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


Date Last Modified: Tuesday, October 30, 2012
Solution ID: 1-BSLVGB
Product: MATLAB Builder NE
Reported in Release: R2009b
Platform: All Platforms
Operating System: All OS
 

Subject:

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)
{

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();
}
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值