C++中调用MatLab接口等

C++ 与 Matlab协作使用比较复杂,逐步学习积累记录,侧重于在C++程序中调用MatLab接口。

环境

Ubuntu 20.04
VS Code
Matlab R2021a for Linux


1. 在 C/C++ 程序中读取和写入 MATLAB 数据

1.1 头文件

Matlab自带供C/C++语言使用的头文件,可在Matlab命令框中输入以下命令来确定其路径,

>> extern_path = [matlabroot '/extern/include']

在这里插入图片描述
然后将头文件路径添加到C++程序中,此外还需要在编译时设置链接,生成可执行文件

g++  -I/usr/local/Matlab/R2021a/extern/include -L/usr/local/Matlab/R2021a/bin/glnxa64 -cpp [需要编译的cpp文件].cpp -o main -lmat -lmx -Wl,-rpath /usr/local/Matlab/R2021a/bin/glnxa64

使用cmake编译程序的话,CMakeLists.txt文件内容如下,此处编译文件mat_test.cpp

cmake_minimum_required(VERSION 3.16)
project(manager_system)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -Wall") # 指定cmake在调用g++编译时的一些输入参数。-g 的作用是编译生成可调式的输出文件,-wall是输出警告信息,-o2这里指的是编译优化
add_subdirectory(src)
include_directories(
    ${CMAKE_SOURCE_DIR}/include
    "/usr/local/Matlab/R2021a/extern/include"
    )

LINK_DIRECTORIES("/usr/local/Matlab/R2021a/bin/glnxa64")
LINK_LIBRARIES("/usr/local/Matlab/R2021a/bin/glnxa64/libeng.so"
    "/usr/local/Matlab/R2021a/bin/glnxa64/libmx.so"
    "/usr/local/Matlab/R2021a/bin/glnxa64/libmat.so")
add_executable(mat_test ${CMAKE_SOURCE_DIR}/src/mat_test.cpp) # 生成可执行文件
target_link_libraries(mat_test SRC) # 将SRC库和main可执行文件链接在一起

set( CMAKE_INSTALL_PREFIX "${CMAKE_SOURCE_DIR}/bin/")
install(TARGETS mat_test RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}) # 这两行将执行文件安装在/bin文件夹下,在/build文件夹下使用命令'make install'

则可以在C++代码中调用Matlab有关的C/C++头文件,如

#include <mat.h>

https://www.cnblogs.com/excellentlhw/p/12009924.html
Matlab官方相关函数介绍

1.2 C MAT 文件 API使用介绍

1.打开mat文件


#include <mat.h>
MATFile *matOpen(const char *filename, const char *mode);

参数

filename
要打开的mat文件的名称

mode
打开mat文件的工作模式,有以下几种:

模式意义
rOpens file for reading only; determines the current version of the MAT-file by inspecting the files and preserves the current version.
uOpens file for update, both reading and writing. If the file does not exist, does not create a file (equivalent to the r+ mode of fopen). Determines the current version of the MAT-file by inspecting the files and preserves the current version.
wOpens file for writing only; deletes previous contents, if any.

返回值
代表mat文件的指针

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值