最近项目要用VC调用MATLAB,今天闲来无事,在这里稍微总结了一下初级的用法,大家共同学习;
首先在MATLAB Command Window里输入mbuild -setup,一步步走
还有一个mex -setup;和上边类似,就不多说了;
写MATLAB函数:
function [sum,prod] = sumandcheng(p1,p2)
sum = p1+p2; % p1 与 p2 的和prod = p1.*p2;end上边函数计算p1和p2的和与积,写它的目的为了测试VC和MATLAB相互传输数据;
在MATLAB串口输入:mcc -W cpplib:plotsintest -T link:lib sumandcheng.m;
等一会生成了plotsintest.lib,plotsintest.h,plotsintest.dll文件,后边要用,把他们拷到你的VC工程目录下;
function [outs] = stringout(inputs)
outs=inputs;
end这个函数直接输出输入的参数,写它的目的为了测试VC和MATLAB相互传输字符串;
同上:mcc -W cpplib:stringtest -T link:lib stringout.m
生成那三个文件stringtest.lib,stringtest.h,stringtest.dll,同样拷到VC工程目录下;
二.VC6.0里设置
1. Project->setting->Link->Object/library modules:加入mclmcrrt.lib和用MATLAB生成的.lib文件;这里用了plotsintest.lib,stringtest.lib;
2.Tools->Options->Directories->Show directories for->include files加入MATLAB的安装路径,例如我D:\ProgramFiles\MATLAB\R2010a\extern\include;接着在Show directories for下的Library files加入D:\ProgramFiles\MATLAB\R2010a\extern\lib\win32\microsoft;
3.加入头文件#include "plotsintest.h",#include "stringtest.h";
4.以下是VC源代码
#include <string.h>
#include <stdlib.h>#include "plotsintest.h"#include "stringtest.h"//***********************以下内容从网上COPY的,不过重加了一遍注释*************************//void display(const double* data, const int r, const int c, const char* name);int main(){ if (! plotsintestInitialize() ){ fprintf(stderr,"Could not initialize the library.\n");exit(1);}double x[] = {1,2,3,4,5,6};//初始化输入序列x;double y[] = {7,8,9,10,11,12};//初始化输入序列y//因为MATLAB里生成dll文件时用的mcc -W cpplib:stringtest -T link:lib stringout.m//所以输入参数必需为mwArray类型;;mwArray X(2,3,mxDOUBLE_CLASS);//定义输入X;mwArray Y(2,3,mxDOUBLE_CLASS);//定义输入Y;X.SetData(x,6);//将x赋值给X;Y.SetData(y,6);//将y赋值给Y;mwArray SUM,PROD;//定义输出mwArray变量;
sumandcheng(2,SUM,PROD,X,Y) ;//2表示输出参数个数,紧接着为输出参数和输入参数//定义输出VC++类型参数,double *sum,*prod;sum = new double[6];prod = new double[6];//取出mwArray型数据并赋值给VC++变量SUM.GetData(sum,6);PROD.GetData(prod,6);//打印出来display(sum,2,3,"SUM");display(prod,2,3,"PROD");delete sum;delete prod;plotsintestTerminate();//***********************以下内容为自己写的*****************************//stringtestInitialize();//看到没,生成的stringtest 加上Initialize,表示初始化;
char strintemp[15]="Hello,World";//定义字符串;
mwArray intstr(strintemp);//把字符串转换为mwArray类型;mwArray outstr;//定义输出字符串;stringout(1,outstr,intstr);//调用MATLAB函数,1表示输出一个变量,紧跟着是输出变量和输入变量;mwString strouttemp=outstr.ToString();//将MATLAB函数输出的mwArray变量换为mwString类型;char *c = strdup((const char *)strouttemp);//把mwString类型转换为char型;printf("%s\n",c);stringtestTerminate();//这个就不解释了吧!return 0;}//当然底下这个子函数也是从网上荡来的和上边是一块的;
void display(const double* data, const int r, const int c, const char* name){ int i,j; printf("%s = \n",name);for(i=0;i<r;i++) { printf("\t");for(j=0;j<c;j++) printf("% 4.2f \t",data[j*r+i]);printf("\n");}printf("\n");}