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中的右侧输入

plhs[0] plhs[1]是输出,需要多少输出变量,那么就在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直接调用。

相关推荐
红宝村村长1 分钟前
Golang交叉编译到Android上运行
android·开发语言·golang
虚行3 分钟前
Go 编程基础
开发语言·后端·golang
脚踏实地的大梦想家7 分钟前
【Go】P14 Go语言核心利器:全面解析结构体 (Struct)
开发语言·后端·golang
QX_hao8 分钟前
【Go】--time包的使用
开发语言·后端·golang
二十雨辰28 分钟前
[作品集]-容易宝
java·开发语言·前端
亮子AI36 分钟前
【NestJS】在 nest.js 项目中,如何使用 Postgresql 来做缓存?
开发语言·缓存·node.js·nest.js
图灵信徒39 分钟前
R语言数据结构与数据处理基础内容
开发语言·数据挖掘·数据分析·r语言
oioihoii1 小时前
高性能推理引擎的基石:C++与硬件加速的完美融合
开发语言·c++
weixin_456904271 小时前
基于C#的文档处理
开发语言·c#
扶苏-su1 小时前
Java---StringBuilder
java·开发语言