|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?我要加入
x
本帖最后由 qibbxxt 于 2011-5-21 13:15 编辑
关于C#调用Matlab的问题,simwe的zccbest已经在前面的帖子里面讲的很详细
我只想在这里说下结构体和单元数组的类型转换问题。
Matlab的结构数组和C#是不同的,而Matlab的单元数组,C#没有,所以在Matlab程序中使用结构数组和单元数组作为输入和输出的时候,如何传化为C#的数据类型,就是一个值得探讨的问题,matlab提供了MWArray程序集可以处理这个问题:
下面是我写的一个m文件:
- function [x,y,z] = StructCellExample(a,b,c)
- if nargin == 0
- a.m = 1;
- a.n = 2;
- b ={rand(2),rand(2)};
- c = 'Hello,World!';
- end
- x = a.m + a.n;
- y = struct('p',cell(size(b)),'q',cell(size(b)));
- for i =1 :length(b)
- y(i).p = sum(b{i}(:));
- y(i).q = max(b{i}(:));
- end
- z = fliplr(c);
复制代码
用deploytool编译成dll,
程序集:SCtest
类:Demo
编写C#代码:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using MathWorks.MATLAB.NET.Arrays.native;
- using SCtestNative;
- namespace StructCellExample
- {
- class Program
- {
- static void Main(string[] args)
- {
- string[] mn = new string[2];
- mn[0] = "m";
- mn[1] = "n";
- double[,] b1 = new double[2, 2];
- double[,] b2 = new double[2, 2];
- b1[0, 0] = 2.3;
- b1[0, 1] = 1.1;
- b1[1, 0] = 1.5;
- b1[1, 1] = 2.9;
- b2[0, 0] = 1.4;
- b2[0, 1] = 2.8;
- b2[1, 0] = 3.1;
- b2[1, 1] = 4.4;
- int[] ib1 = new int[2];
- ib1[0] = 1;
- ib1[1] = 1;
- int[] ib2 = new int[2];
- ib2[0] = 1;
- ib2[1] = 2;
- MWStructArray a = new MWStructArray(1, 1, mn);
- a.SetField(mn[0], 1);
- a.SetField(mn[1], 2);
- MWCellArray b = new MWCellArray(1, 2);
- b[ib1] = b1;
- b[ib2] = b2;
- string c = "Hello, World";
- Demo MyTest = new Demo();
- object[] xyz = MyTest.StructCellExample(3, a, b, c);
- int[,] x = (int[,])xyz[0];
- MWStructArray y = (MWStructArray)xyz[1];
- string[] pq = y.FieldNames;
- double[,] y1p = (double[,])y.GetField(pq[0], 1);
- double[,] y1q = (double[,])y.GetField(pq[1], 1);
- double[,] y2p = (double[,])y.GetField(pq[0], 2);
- double[,] y2q = (double[,])y.GetField(pq[1], 2);
- char[,] z = (char[,])xyz[2];
- Console.WriteLine("程序运行完毕");
- Console.WriteLine("输出第一个返回参数");
- Console.WriteLine("a={0}", x[0, 0]);
- Console.WriteLine("输出第二个返回参数");
- Console.WriteLine("y(1).{0}={1}", pq[0], y1p[0, 0]);
- Console.WriteLine("y(1).{0}={1}", pq[1], y1q[0, 0]);
- Console.WriteLine("y(2).{0}={1}", pq[0], y2p[0, 0]);
- Console.WriteLine("y(2).{0}={1}", pq[1], y2q[0, 0]);
- Console.WriteLine("输出第三个返回参数");
- foreach (char i in z)
- Console.Write(i);
- Console.WriteLine(System.Environment.NewLine);
- }
- }
- }
复制代码 运行:
|
评分
-
2
查看全部评分
-
|