最近写了个Matlab程序,好慢呐……所以开始学习Matlab与C/C++混合编程。下面写了个测试代码,显示一个Double类型矩阵中的元素。

源代码

#include "mex.h"

void displaySubscript( const mxArray *pArray, mwSize index );

// 入口函数
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) {
    
    // 源文件名后缀为.c时,所有变量声明必须一次性完成,且放在最前面, 否则mex编译错误
    // 源文件名后缀为.cpp时,没有上面的问题,...- -||
    double *pData;
    mwSize i;
    
    // 输入参数必须为一个,且为double类型
    if ( nrhs != 1 || mxDOUBLE_CLASS != mxGetClassID(prhs[0]) ) {
        mexErrMsgTxt( "输入参数不合法……" );
    }
    
    // 获取数据指针
    pData = mxGetPr(prhs[0]);
    
    // 遍历所有元素并打印到屏幕
    for ( i = 0; i != mxGetNumberOfElements(prhs[0]); i++ ) {
        displaySubscript( prhs[0], i );
        mexPrintf( " = %g/n", pData[i] );
    }
}

void displaySubscript( const mxArray *pArray, mwSize index ) {
    
    // 源文件名后缀为.c时,所有变量声明必须一次性完成,且放在最前面, 否则mex编译错误
    // 源文件名后缀为.cpp时,没有上面的问题,...- -||,代码好龊...
    mwSize i, j;
    mwSize numOfDim;
    mwSize *subScript;
    mwSize subIndex;
    mwSize total;
    
    const mwSize *Dims;
    const char *className;
    
    // 获取维度个数
    numOfDim = mxGetNumberOfDimensions(pArray);
    // 获取维度数组
    Dims = mxGetDimensions(pArray);
    // 获取类型名称
    className = mxGetClassName(pArray);
    // 分配下标数组内存
    subScript = (mwSize *)mxCalloc( numOfDim, sizeof( mwSize ) );
    
    // 根据当前的索引号生成下标
    subIndex = index;
    for ( i = numOfDim - 1; ; i-- ) {
        total = 1;
        
        for ( j = 0; j < i; j++ ) {
            total *= Dims[j];
        }
        
        subScript[i] = subIndex / total;
        subIndex = subIndex % total;
        
        if ( 0 == i ) {
            break;
        }
    }
    
    // 打印出所有下标
    mexPrintf( "(" );
    for ( i = 0; i < numOfDim - 1; i++ ) {
        mexPrintf( "%d,", subScript[i] + 1 );
    }
    mexPrintf( "%d)", subScript[numOfDim-1] + 1 );
    
    // 释放下标数组内存
    mxFree( subScript );
}

在Matlab使用mex命令编译源文件时,要注意这样一个现象:源文件名后缀为.c时,所有变量声明必须一次性完成,且放在最前面, 否则mex编译错误;而源文件名后缀为.cpp时,就没有上面的问题,...- -||。

实验结果

混合编程API一览

MX Matrix Library

mwIndex (C and Fortran)

Type for index values

mwPointer (Fortran)

Pointer type for platform

mwSignedIndex (C and Fortran)

Signed integer type for size values

mwSize (C and Fortran)

Type for size values

mxAddField (C and Fortran)

Field to structure array

mxArray (C and Fortran)

Type for MATLAB array

mxArrayToString (C)

Convert array to string

mxAssert (C)

Check assertion value for debugging purposes

mxAssertS (C)

Check assertion value without printing assertion text

mxCalcSingleSubscript (C and Fortran)

Offset from first element to desired element

mxCalloc (C and Fortran)

Allocate dynamic memory for array using MATLAB memory manager

mxChar (C)

Type for string array

mxClassID (C)

Enumerated value identifying class of array

mxClassIDFromClassName (Fortran)

Identifier corresponding to class

mxComplexity (C)

Flag specifying whether array has imaginary components

mxCopyCharacterToPtr (Fortran)

CHARACTER values from Fortran array to pointer array

mxCopyComplex16ToPtr (Fortran)

COMPLEX*16 values from Fortran array to pointer array

mxCopyComplex8ToPtr (Fortran)

COMPLEX*8 values from Fortran array to pointer array

mxCopyInteger1ToPtr (Fortran)

INTEGER*1 values from Fortran array to pointer array

mxCopyInteger2ToPtr (Fortran)

INTEGER*2 values from Fortran array to pointer array

mxCopyInteger4ToPtr (Fortran)

INTEGER*4 values from Fortran array to pointer array

mxCopyPtrToCharacter (Fortran)

CHARACTER values from pointer array to Fortran array

mxCopyPtrToComplex16 (Fortran)

COMPLEX*16 values from pointer array to Fortran array

mxCopyPtrToComplex8 (Fortran)

COMPLEX*8 values from pointer array to Fortran array

mxCopyPtrToInteger1 (Fortran)

INTEGER*1 values from pointer array to Fortran array

mxCopyPtrToInteger2 (Fortran)

INTEGER*2 values from pointer array to Fortran array

mxCopyPtrToInteger4 (Fortran)

INTEGER*4 values from pointer array to Fortran array

mxCopyPtrToPtrArray (Fortran)

Pointer values from pointer array to Fortran array

mxCopyPtrToReal4 (Fortran)

REAL*4 values from pointer array to Fortran array

mxCopyPtrToReal8 (Fortran)

REAL*8 values from pointer array to Fortran array

mxCopyReal4ToPtr (Fortran)

REAL*4 values from Fortran array to pointer array

mxCopyReal8ToPtr (Fortran)

REAL*8 values from Fortran array to pointer array

mxCreateCellArray (C and Fortran)

Unpopulated N-D cell array

mxCreateCellMatrix (C and Fortran)

Unpopulated 2-D cell array

mxCreateCharArray (C and Fortran)

Unpopulated N-D string array

mxCreateCharMatrixFromStrings (C and Fortran)

Create populated 2-D string array

mxCreateDoubleMatrix (C and Fortran)

2-D, double-precision, floating-point array initialized to 0

mxCreateDoubleScalar (C and Fortran)

Scalar, double-precision array initialized to specified value

mxCreateLogicalArray (C)

N-D logical array initialized to false

mxCreateLogicalMatrix (C)

2-D, logical array initialized to false

mxCreateLogicalScalar (C)

Scalar, logical array

mxCreateNumericArray (C and Fortran)

Unpopulated N-D numeric array

mxCreateNumericMatrix (C and Fortran)

Numeric matrix initialized to 0

mxCreateSparse (C and Fortran)

2-D unpopulated sparse array

mxCreateSparseLogicalMatrix (C)

Unpopulated 2-D, sparse, logical array

mxCreateString (C and Fortran)

Create 1-by-N array initialized to specified string

mxCreateStructArray (C and Fortran)

Unpopulated N-D structure array

mxCreateStructMatrix (C and Fortran)

Unpopulated 2-D structure array

mxDestroyArray (C and Fortran)

Free dynamic memory allocated by MXCREATE* functions

mxDuplicateArray (C and Fortran)

Make deep copy of array

mxFree (C and Fortran)

Free dynamic memory allocated by MXCALLOC, MXMALLOC, or MXREALLOC functions

mxGetCell (C and Fortran)

Contents of array cell

mxGetChars (C)

Pointer to character array data

mxGetClassID (C and Fortran)

Class of array

mxGetClassName (C and Fortran)

Class of array as string

mxGetData (C and Fortran)

Pointer to real data

mxGetDimensions (C and Fortran)

Pointer to dimensions array

mxGetElementSize (C and Fortran)

Number of bytes required to store each data element

mxGetEps (C and Fortran)

Value of EPS

mxGetField (C and Fortran)

Field value, given field name and index, into structure array

mxGetFieldByNumber (C and Fortran)

Field value, given field number and index, into structure array

mxGetFieldNameByNumber (C and Fortran)

Field name, given field number, in structure array

mxGetFieldNumber (C and Fortran)

Field number, given field name, in structure array

mxGetImagData (C and Fortran)

Pointer to imaginary data of array

mxGetInf (C and Fortran)

Value of infinity

mxGetIr (C and Fortran)

Sparse matrix IR array

mxGetJc (C and Fortran)

Sparse matrix JC array

mxGetLogicals (C)

Pointer to logical array data

mxGetM (C and Fortran)

Number of rows in array

mxGetN (C and Fortran)

Number of columns in array

mxGetNaN (C and Fortran)

Value of NaN (Not-a-Number)

mxGetNumberOfDimensions (C and Fortran)

Number of dimensions in array

mxGetNumberOfElements (C and Fortran)

Number of elements in array

mxGetNumberOfFields (C and Fortran)

Number of fields in structure array

mxGetNzmax (C and Fortran)

Number of elements in IR, PR, and PI arrays

mxGetPi (C and Fortran)

Imaginary data elements in array of type DOUBLE

mxGetPr (C and Fortran)

Real data elements in array of type DOUBLE

mxGetProperty (C and Fortran)

Value of public property of MATLAB object

mxGetScalar (C and Fortran)

Real component of first data element in array

mxGetString (C and Fortran)

String array to C-style string

mxIsCell (C and Fortran)

Determine whether input is cell array

mxIsChar (C and Fortran)

Determine whether input is string array

mxIsClass (C and Fortran)

Determine whether array is member of specified class

mxIsComplex (C and Fortran)

Determine whether data is complex

mxIsDouble (C and Fortran)

Determine whether mxArray represents data as double-precision, floating-point numbers

mxIsEmpty (C and Fortran)

Determine whether array is empty

mxIsFinite (C and Fortran)

Determine whether input is finite

mxIsFromGlobalWS (C and Fortran)

Determine whether array was copied from MATLAB global workspace

mxIsInf (C and Fortran)

Determine whether input is infinite

mxIsInt16 (C and Fortran)

Determine whether array represents data as signed 16-bit integers

mxIsInt32 (C and Fortran)

Determine whether array represents data as signed 32-bit integers

mxIsInt64 (C and Fortran)

Determine whether array represents data as signed 64-bit integers

mxIsInt8 (C and Fortran)

Determine whether array represents data as signed 8-bit integers

mxIsLogical (C and Fortran)

Determine whether array is of type mxLogical

mxIsLogicalScalar (C)

Determine whether scalar array is of type mxLogical

mxIsLogicalScalarTrue (C)

Determine whether scalar array of type mxLogical is true

mxIsNaN (C and Fortran)

Determine whether input is NaN (Not-a-Number)

mxIsNumeric (C and Fortran)

Determine whether array is numeric

mxIsSingle (C and Fortran)

Determine whether array represents data as single-precision, floating-point numbers

mxIsSparse (C and Fortran)

Determine whether input is sparse array

mxIsStruct (C and Fortran)

Determine whether input is structure array

mxIsUint16 (C and Fortran)

Determine whether array represents data as unsigned 16-bit integers

mxIsUint32 (C and Fortran)

Determine whether array represents data as unsigned 32-bit integers

mxIsUint64 (C and Fortran)

Determine whether array represents data as unsigned 64-bit integers

mxIsUint8 (C and Fortran)

Determine whether array represents data as unsigned 8-bit integers

mxLogical (C)

Type for logical array

mxMalloc (C and Fortran)

Allocate dynamic memory using MATLAB memory manager

mxRealloc (C and Fortran)

Reallocate dynamic memory using MATLAB memory manager

mxRemoveField (C and Fortran)

Remove field from structure array

mxSetCell (C and Fortran)

Value of one cell of array

mxSetClassName (C)

Convert structure array to MATLAB object array

mxSetData (C and Fortran)

Set pointer to data

mxSetDimensions (C and Fortran)

Modify number of dimensions and size of each dimension

mxSetField (C and Fortran)

Set structure array field, given structure field name and array index

mxSetFieldByNumber (C and Fortran)

Set structure array field, given field number and index

mxSetImagData (C and Fortran)

Imaginary data pointer for array

mxSetIr (C and Fortran)

IR array of sparse array

mxSetJc (C and Fortran)

JC array of sparse array

mxSetM (C and Fortran)

Number of rows in array

mxSetN (C and Fortran)

Set number of columns in array

mxSetNzmax (C and Fortran)

Set storage space for nonzero elements

mxSetPi (C and Fortran)

Set new imaginary data for array

mxSetPr (C and Fortran)

Set new real data for array

mxSetProperty (C and Fortran)

Set value of public property of MATLAB object

MEX Library

mexAtExit (C and Fortran)

Register function to call when MEX-function cleared or MATLAB software terminates

mexCallMATLAB (C and Fortran)

Call MATLAB function, user-defined function, or MEX-file

mexCallMATLABWithTrap (C and Fortran)

Call MATLAB function, user-defined function, or MEX-file and capture error information

mexErrMsgIdAndTxt (C and Fortran)

Display error message with identifier and return to MATLAB prompt

mexErrMsgTxt (C and Fortran)

Display error message and return to MATLAB prompt

mexEvalString (C and Fortran)

Execute MATLAB command in caller workspace

mexEvalStringWithTrap (C and Fortran)

Execute MATLAB command in caller workspace and capture error information

mexFunction (C and Fortran)

Entry point to C/C++ or Fortran MEX-file

mexFunctionName (C and Fortran)

Name of current MEX-function

mexGet (C)

Value of specified Handle Graphics property

mexGetVariable (C and Fortran)

Copy of variable from specified workspace

mexGetVariablePtr (C and Fortran)

Read-only pointer to variable from another workspace

mexIsGlobal (C and Fortran)

Determine whether variable has global scope

mexIsLocked (C and Fortran)

Determine whether MEX-file is locked

mexLock (C and Fortran)

Prevent clearing MEX-file from memory

mexMakeArrayPersistent (C and Fortran)

Make array persist after MEX-file completes

mexMakeMemoryPersistent (C and Fortran)

Make memory allocated by MATLAB software persist after MEX-function completes

mexPrintf (C and Fortran)

ANSI C PRINTF-style output routine

mexPutVariable (C and Fortran)

Array from MEX-function into specified workspace

mexSet (C)

Set value of specified Handle Graphics property

mexSetTrapFlag (C and Fortran)

Control response of MEXCALLMATLAB to errors

mexUnlock (C and Fortran)

Allow clearing MEX-file from memory

mexWarnMsgIdAndTxt (C and Fortran)

Warning message with identifier

mexWarnMsgTxt (C and Fortran)

Warning message

Matlab与C/C++联合编程之Matlab以MEX方式调用C/C++代码(三)的更多相关文章

  1. Matlab与C/C++联合编程之Matlab以MEX方式调用C代码(五)完整过程加示

    如下为本人亲证代码: 一: 编译器的安装与配置(环境不同,显示结果不同) 要使用MATLAB编译器,用户计算机上应用事先安装与MATLAB适配的以下任何一种ANSI C/C++编译器: 5.0.6.0 ...

  2. Matlab与C/C++联合编程之Matlab以MEX方式调用C/C++代码(四)

    利用Matlab与VC++联合编程,既可在C语言程序中打开Matlab引擎,调用Matlab的ToolBox函数和作图函数,也可在Matlab中调用C代码生成的动态链接库文件,用以加快执行速度.缩短开 ...

  3. Matlab与C/C++联合编程之Matlab以MEX方式调用C/C++代码(一)

    MEX文件是一种可在matlab环境中调用的C语言(或fortran)衍生程序,mex的编译结果实际上就是一个带输出函数mexFunction 的dll文件. 中文名 mex文件 外文名 MATLAB ...

  4. Matlab与C/C++联合编程之Matlab以MEX方式调用C/C++代码(二)

    如果我有一个用C语言写的函数,实现了一个功能,如一个简单的函数: double add(double x, double y) { return x + y; } 现在我想要在Matlab中使用它,比 ...

  5. Matlab以MEX方式调用C源代码【转载】

    原文地址:http://blog.sina.com.cn/s/blog_468651400100coas.html 这是自己整理的一个对应的文档:<Matlab以MEX方式调用C源代码> ...

  6. Matlab以MEX方式调用C源代码

    #include "mex.h" // 使用MEX文件必须包含的头文件 // 执行具体工作的C函数 double add(double x, double y) { return ...

  7. matlab中文论坛视频谷普教程MATLAB压缩包介绍

    matlab中文论坛视频谷普教程MATLAB压缩包介绍 我也正在学习这个软件 ,看到这个教程就在这里分享了,希望大家喜欢!Matlab 初学者视频教学1. Matlab视频:Matlab中文论坛为新手 ...

  8. Matlab中调用第三方Java代码

    搞了一天,才算搞定. 第一步:定位Matlab中Java环境的ext目录 新建一个M script文件,或者直接在Matlab的交互式命令行中输入: disp(java.lang.System.get ...

  9. MATLAB/Excel-如何将Excel数据导入MATLAB中

    在使用MATLAB对矩阵进行数据处理时,为了方便编辑与修改,常常需要先将数据录入到Excel中,然后再将其导入到MATLAB中参与矩阵运算.本文在MATLAB 2013a和Office 2013环境下 ...

随机推荐

  1. Asp.NET设置Session过期时间的四种方式

    在Asp.net中,可以有四处设置Session的过期时间: 一.全局网站(即服务器)级 IIS-网站-属性-Asp.net-编辑配置-状态管理-会话超时(分钟)-设置为120,即为2小时,即120分 ...

  2. Android LayoutParams

    LayoutParams继承于Android.View.ViewGroup.LayoutParams,就是布局. LayoutParams相当于一个Layout的信息包,它封装了Layout的位置.高 ...

  3. ie8 table td拆分宽度不适应问题

    在table上加style="table-layout: fixed;"并在首行加一个高度为0且给定宽度的tr <table class="subtabledeta ...

  4. web前端页面性能优化小结

    影响用户访问的最大部分是前端的页面.网站的划分一般为二:前端和后台.我们可以理解成后台是用来实现网站的功能的,比如:实现用户注册,用户能够为文章发表评论等等.而前端呢?其实应该是属于功能的表现. 而我 ...

  5. jmeter 建立一个JMS主题测试计划

    创建两个线程组和组 每一个到10迭代. 总消息线程(6)x(1消息) (重复10次)= 60消息. 建立测试计划,您将使用 以下元素: 线程组 , JMS的出版商 , JMS用户 , 图结果 . 一般 ...

  6. python 练习 9

    #!/usr/bin/python # -*- coding: UTF-8 -*- for i in range(1,5): for j in range(1,5): for k in range(1 ...

  7. 简单的Hibernate入门简介

    其实Hibernate本身是个独立的框架,它不需要任何web server或application server的支持.然而,大多数的Hibernate入门介绍都加入了很多非Hibernate的东西, ...

  8. centos nginx 安装

    1.下载 wget http://nginx.org/download/nginx-1.7.8.tar.gz 2.解压 tar -zxvf nginx-1.7.8.tar.gz 3.切换目录 cd n ...

  9. jQuery图表开源软件

    jQuery图表插件 jQchart jQchart 是一个jQuery的插件,用来绘制图表的.支持各种形状的图表. 示例代码: == Mini sample == $('#canvasMyID'). ...

  10. $('#checkbox').attr('checked'); 返回的是checked或者是undefined解决办法

    $('#checkbox').attr('checked'); 返回的是checked或者是undefined解决办法 <input type='checkbox' id='cb'/>  ...