Matlab调C/C++简单模板例子

如果你是需要快速搭建一个matlab调c/c++环境,这篇文章可以参考

有了c代码,想在matlab里面调用,可以参考我这个模板

matlab调用代码:

复制代码
clear all
close all
clc

input1 =1;
input2 =2;

[output1,output2] = mexfunction(input1,input2);

output1
output2

这里面强调两个概念

1、Matlab里面所有变量都是矩阵,包括单变量也是1*1的矩阵

2、Maltab矩阵按列优先访问,这个和fortran保持一致

Cpp代码:

复制代码
#include "mex.h"

void c_func(double input1,double input2,double *output1,double *output2) 
{
    
}


void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) 
{	
	double *pdata; 
	// mcnoidal(waveheight,waveperiod,0.02,waterdeepth ,0, datanum,1, waveheight,flapdeepth);
     
	pdata=mxGetPr(prhs[0]); 
	double input1 = *pdata;
 	
    int M = mxGetM(prhs[0]);
    int N = mxGetN(prhs[0]);
    
    printf("%d * %d\n",M,N);
    
 	pdata=mxGetPr(prhs[1]); 
	double input2 = *pdata;
	
	int m = 3;
	int n = 2;
	plhs[0] = mxCreateDoubleMatrix(m, n, mxREAL); 
	double *output1;	
	output1 = mxGetPr( plhs[0]);
 	
    //列优先排列
 	output1[0*m+0] = 1;
    output1[1*m+0] = 2;
 	output1[0*m+1] = 3;
    output1[1*m+1] = 4;
 	output1[0*m+2] = 5;
    output1[1*m+2] = 6; 	
 	
 	plhs[1] = mxCreateDoubleMatrix(1, 1, mxREAL); 
    double *output2;
    output2 = mxGetPr( plhs[1]);
    output2[0] = -1;
    
    
    //c_func(input1,input2,output1,output2) ;
    
 	

 	
 	
}

plhs 全称 parameters left matlab中的左侧输出

prhs全称 parameters left matlab中的右侧输入

plhs0 plhs1是输出,需要多少输出变量,那么就在c中用mxCreateDoubleMatrix申请多少

所有的数字,数组,二位数字,到c这边都是一维数组,且按列优先访问。

输出如下

注三行两列的二维数组访问方式:

复制代码
int m=3;
int n=2;
//内存列优先排列,但赋值按逐行赋值
output1[0*m+0] = 1;
output1[1*m+0] = 2;
output1[0*m+1] = 3;
output1[1*m+1] = 4;
output1[0*m+2] = 5;
output1[1*m+2] = 6;

//列优先排列,但按列赋值
output1[0*m+0] = 1;
output1[0*m+1] = 3;
output1[0*m+2] = 5;
output1[1*m+0] = 2;
output1[1*m+1] = 4;
output1[1*m+2] = 6;

//另:行优先排列,按行赋值
output1[0*n+0] = 1;
output1[0*n+1] = 2;
output1[1*n+0] = 3;
output1[1*n+1] = 4;
output1[2*n+0] = 5;
output1[2*n+1] = 6;

在matlab 使用mex 编译一下(预先需要mex setup)

mex mexFunction.cpp 即可编译,然后在malab直接调用。

相关推荐
LDR0066 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术6 天前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript
码云数智-园园6 天前
C++20 Modules 模块详解
java·开发语言·spring
xiao5kou4chang6kai46 天前
MATLAB机器学习、深度学习--从数据预处理到模型训练
深度学习·机器学习·matlab·数据预处理
swordbob6 天前
NIO的channel中什么是 fd(File Descriptor,文件描述符)
java·开发语言·nio
源分享6 天前
Java线程同步的多种实现方法(非常详细)
java·开发语言·jvm
Luminous.6 天前
C语言--day30
c语言·开发语言
何以解忧,唯有..6 天前
Go语言循环语句详解:for、range与循环控制
开发语言·算法·golang
謓泽6 天前
C语言不是语法,是通往机器的地图。
c语言·开发语言
云水一下6 天前
从零开始学 PHP 系列(一):PHP 的前世今生与开发环境搭建
开发语言·php