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直接调用。

相关推荐
ShineWinsu9 分钟前
对于Qt:QFormLayout常见属性以及方法的解析
开发语言·c++·qt·面试·客户端·表单·qformlayout
水桶学习吧_4 小时前
基于MATLAB的圆锥滚子轴承故障诊断仿真
matlab·故障诊断·圆锥滚子轴承
利威尔xu5 小时前
Go channel 关闭 3 个 panic:向已关闭 channel 发送,服务当场崩溃
开发语言·后端·golang·并发编程·channel
山楂树の5 小时前
Java BigDecimal笔记
java·开发语言
Java展博8 小时前
[Go 后端转场] 从 try-catch 到 if err != nil:写惯 Java 的人第一次上手最别扭的 4 件事
java·开发语言·golang
SEO_juper8 小时前
Node.js 全站 SEO 体检报告生成器:一次查完标题、描述、canonical、H1、图片
开发语言·前端·node.js·html·bash
风落青芜9 小时前
数据结构:堆的概念与实现
c语言·开发语言·数据结构·算法
H H.12 小时前
Java企业级开发:从框架到工程化实战
java·开发语言·经验分享·其他·课程设计
吃我一窝jio1 天前
Python与Go线程模型深度对比
java·开发语言·python
eggwyw1 天前
C++ union 的一种妙用法
开发语言·c++