[Matlab]VS和Matlab混合编程(相关API使用-进阶)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/humanking7/article/details/85939988


原创文章,欢迎转载。转载请注明:转载自 祥的博客

原文链接:https://blog.csdn.net/humanking7/article/details/85939988


VS和Matlab混合编程(相关API使用-进阶)

如何调用Matlab Engine以及相关配置,见前文:VS和Matlab混合编程(调用Matlab Engine)

环境以及配置

  • Window7 x64
  • VS2015
  • Matlab R2013a x64

1.相关API

这里只是给列出大概,详情还得查Matlab的帮助文档,详见:C/C++ Matrix Library API

1.1. Data Types

mxArray	//Type for MATLAB array
mxClassID	//Enumerated value identifying class of array
mwSize	//Type for size values
mwIndex	//Type for index values
mwSignedIndex	//Signed integer type for size values
mxChar	//Type for string array
mxLogical	//Type for logical array
mxComplexity	//Flag specifying whether array has imaginary components
mxGetEps	//Value of EPS
mxGetInf	//Value of infinity
mxGetNaN	//Value of NaN (Not-a-Number)

1.2. Create or Delete Array

mxCreateDoubleMatrix	//2-D, double-precision, floating-point array
mxCreateDoubleScalar	//Scalar, double-precision array initialized to specified value
mxCreateNumericMatrix	//2-D numeric matrix
mxCreateNumericArray	//N-D numeric array
mxCreateUninitNumericMatrix	//Uninitialized 2-D numeric matrix
mxCreateUninitNumericArray	//Uninitialized N-D numeric array
mxCreateString	//1-N array initialized to specified string
mxCreateCharMatrixFromStrings	//2-D mxChar array initialized to specified value
mxCreateCharArray	//N-D mxChar array
mxCreateLogicalScalar	//Scalar, logical array
mxCreateLogicalMatrix	//2-D logical array
mxCreateLogicalArray	//N-D logical array
mxCreateSparseLogicalMatrix	//2-D, sparse, logical array
mxCreateSparse	//2-D sparse array
mxCreateSparseLogicalMatrix	//2-D, sparse, logical array
mxCreateStructMatrix	//2-D structure array
mxCreateStructArray	//N-D structure array
mxCreateCellMatrix	//2-D cell array
mxCreateCellArray	//N-D cell array
mxDestroyArray	//Free dynamic memory allocated by MXCREATE* functions
mxDuplicateArray	//Make deep copy of array
mxCalloc	//Allocate dynamic memory for array, initialized to 0, using MATLAB memory manager
mxMalloc	//Allocate uninitialized dynamic memory using MATLAB memory manager
mxRealloc	//Reallocate dynamic memory using MATLAB memory manager
mxFree	//Free dynamic memory allocated by mxCalloc, mxMalloc, mxRealloc, mxArrayToString, or mxArrayToUTF8String functions

1.3. Validate Data

mxIsDouble	//Determine whether mxArray represents data as double-precision, floating-point numbers
mxIsSingle	//Determine whether array represents data as single-precision, floating-point numbers
mxIsComplex	//Determine whether data is complex
mxIsNumeric	//Determine whether array is numeric
mxIsInt64	//Determine whether array represents data as signed 64-bit integers
mxIsUint64	//Determine whether array represents data as unsigned 64-bit integers
mxIsInt32	//Determine whether array represents data as signed 32-bit integers
mxIsUint32	//Determine whether array represents data as unsigned 32-bit integers
mxIsInt16	//Determine whether array represents data as signed 16-bit integers
mxIsUint16	//Determine whether array represents data as unsigned 16-bit integers
mxIsInt8	//Determine whether array represents data as signed 8-bit integers
mxIsUint8	//Determine whether array represents data as unsigned 8-bit integers
mxIsScalar	//Determine whether array is scalar array
mxIsChar	//Determine whether input is mxChar array
mxIsLogical	//Determine whether array is of type mxLogical
mxIsLogicalScalar	//Determine whether scalar array is of type mxLogical
mxIsLogicalScalarTrue	//Determine whether scalar array of type mxLogical is true
mxIsStruct	//Determine whether input is structure array
mxIsCell	//Determine whether input is cell array
mxIsClass	//Determine whether array is object of specified class
mxIsInf	//Determine whether input is infinite
mxIsFinite	//Determine whether input is finite
mxIsNaN	//Determine whether input is NaN (Not-a-Number)
mxIsEmpty	//Determine whether array is empty
mxIsSparse	//Determine whether input is sparse array
mxIsFromGlobalWS	//Determine whether array was copied from MATLAB global workspace
mxAssert	//Check assertion value for debugging purposes
mxAssertS	//Check assertion value without printing assertion text

1.4. Access Data

mxGetNumberOfDimensions	//Number of dimensions in array
mxGetElementSize	//Number of bytes required to store each data element
mxGetDimensions	//Pointer to dimensions array
mxSetDimensions	//Modify number of dimensions and size of each dimension
mxGetNumberOfElements	//Number of elements in array
mxCalcSingleSubscript	//Offset from first element to desired element
mxGetM	//Number of rows in array
mxSetM	//Set number of rows in array
mxGetN	//Number of columns in array
mxSetN	//Set number of columns in array
mxGetScalar	//Real component of first data element in array
mxGetPr	//Real data elements in array of type DOUBLE
mxSetPr	//Set new real data elements in array of type DOUBLE
mxGetPi	//Imaginary data elements in array of type DOUBLE
mxSetPi	//Set new imaginary data elements in array of type DOUBLE
mxGetData	//Pointer to real numeric data elements in array
mxSetData	//Set pointer to real numeric data elements in array
mxGetImagData	//Pointer to imaginary data elements in array
mxSetImagData	//Set pointer to imaginary data elements in array
mxGetChars	//Pointer to character array data
mxGetLogicals	//Pointer to logical array data
mxGetClassID	//Class of array
mxGetClassName	//Class of array as string
mxSetClassName	//Structure array to MATLAB object array
mxGetProperty	//Value of public property of MATLAB object
mxSetProperty	//Set value of public property of MATLAB object
mxGetField	//Pointer to field value from structure array, given index and field name
mxSetField	//Set field value in structure array, given index and field name
mxGetNumberOfFields	//Number of fields in structure array
mxGetFieldNameByNumber	//Pointer to field name from structure array, given field number
mxGetFieldNumber	//Field number from structure array, given field name
mxGetFieldByNumber	//Pointer to field value from structure array, given index and field number
mxSetFieldByNumber	//Set field value in structure array, given index and field number
mxAddField	//Add field to structure array
mxRemoveField	//Remove field from structure array
mxGetCell	//Pointer to element in cell array
mxSetCell	//Set contents of cell array
mxGetNzmax	//Number of elements in IR, PR, and PI arrays
mxSetNzmax	//Set storage space for nonzero elements
mxGetIr	//Sparse matrix IR array
mxSetIr	//IR array of sparse array
mxGetJc	//Sparse matrix JC array
mxSetJc	//JC array of sparse array

1.5. Convert Data Types

mxArrayToString	//Array to string
mxArrayToUTF8String	//Array to string in UTF-8 encoding
mxGetString	//mxChar array to C-style string or Fortran character array
mxSetClassName	//Structure array to MATLAB object array

2. API使用代码

#include <iostream>
#include <string>

using namespace std;

#include "engine.h"   //调用matlab函数的头文件

#pragma comment(lib,"libeng.lib")
#pragma comment(lib,"libmx.lib")
#pragma comment(lib,"libmex.lib")
int main()
{

	cout << "正在打开Matlab engine ..." << endl;

	Engine* ep; //定义engine类型指针,往后函数都要用它来指示目标
	ep = engOpen(NULL); //启动函数,成功则返回一个非零值 
	if (ep == NULL) {
		cout << "无法打开 Matlab engine!" << endl;
		return 1;
	}
	else
	{
		cout << "Matlab Engine 启动成功" << endl;
	}


	//=====================
	// Example.1
	// 计算 a + b 的值
	//=====================
	mxArray *sumArray = NULL;
	double a = 1.1, b = 2.2;
	string strTmp = "sum=" + to_string(a) + '+' + to_string(b);
	engEvalString(ep, strTmp.c_str());   //在Matlab命令行输入: sum=a+b;
	sumArray = engGetVariable(ep, "sum");  //获取工作空间中sum变量,它得到的是一个mxArray数组指针
	double sumValue = *(mxGetPr(sumArray));  //double *mxGetPr(const mxArray *pm);
	cout << "Example1:\n  sum = "<<sumValue << endl;
	mxDestroyArray(sumArray); //释放空间



	//=====================
	// Example.2
	// 计算两个向量的值
	// v1 = [1, 2, 3, 4]; v2 = [0.4, 0.3, 0.2, 0.1]
	//=====================
	mxArray *v1_array = NULL, *v2_array = NULL, *vSum_array = NULL;
	const double v1_double[] = { 1, 2, 3, 4 };
	const double v2_double[] = { 0.4, 0.3, 0.2, 0.1 };
	v1_array = mxCreateDoubleMatrix(1, 4, mxREAL); //对v1进行分配存储空间
	v2_array = mxCreateDoubleMatrix(1, 4, mxREAL); //对v2进行分配存储空间
	memcpy((void *)mxGetPr(v1_array), (void *)v1_double, 4 * sizeof(v1_double[0]));  //对v1赋值
	memcpy((void *)mxGetPr(v2_array), (void *)v2_double, 4 * sizeof(v2_double[0]));  //对v2赋值                                                                 

	engPutVariable(ep, "v1", v1_array); //给Matlab工作空间添加变量,相当于  >> v1 = [1, 2, 3, 4]; 
	engPutVariable(ep, "v2", v2_array); //给Matlab工作空间添加变量,相当于  >> v2 = [0.4, 0.3, 0.2, 0.1]

	engEvalString(ep, "vSum = v1 + v2");
	vSum_array = engGetVariable(ep, "vSum");
	size_t sizeV = mxGetNumberOfElements( vSum_array ); //size_t mxGetNumberOfElements(const mxArray *pm);
	cout << "Example2:\n  向量vSum的元素个数:" << sizeV << endl;
	double* pElemVSum = mxGetPr(vSum_array); //指向vSum首地址的指针
	for (int i=0;i<sizeV;i++)
	{
		strTmp = "  vSum[" + to_string(i) + "] = ";
		cout << strTmp << *pElemVSum << endl;
		pElemVSum++;
	}	


	mxDestroyArray(v1_array); //释放空间
	mxDestroyArray(v2_array);
	mxDestroyArray(vSum_array);


	engEvalString(ep, "close;");
	engClose(ep);

	system("pause");
	return 0;

}

赞赏码New

猜你喜欢

转载自blog.csdn.net/humanking7/article/details/85939988
今日推荐