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文件的工作模式,有以下几种:
模式 | 意义 |
---|
r | Opens file for reading only; determines the current version of the MAT-file by inspecting the files and preserves the current version. | u | Opens 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. | w | Opens file for writing only; deletes previous contents, if any. |
返回值 代表mat文件的指针
|