How do I work with variables from .mat files (mxArray) and pass them to Matlab functions in C++?

2 views (last 30 days)
so I needed to read some variables from a .mat file using my C++ code, so I naturally used the C Matrix API (for example: `mat.h`) to get access to functions like `matOpen` or `matGetVariable` and it stores said variables in `mxArray` variables
Thing is, I need these said variables to use in my generated Matlab functions Matlab functions I compiled as C++ shared libraries and now use in C++.
However, these functions only accept `mwArray` not `mxArray` variables.
Is there a way around this?
There has to be, but I really can't see it atm, so any help would be highly appreciated!

Answers (1)

Eswaramoorthy
Eswaramoorthy on 1 Mar 2023
Hi, From your question, I get to understand that, your finding a way to convert the 'mxArray' type variable to 'mwArary' type variable. There is a way to convert mxArray variables to mwArray variables so that you can use them in your C++ shared libraries.
To convert an mxArray variable to an mwArray variable, you can use the mwArray constructor that takes an mxArray argument. Here's an example:
#include "mat.h"
#include "matrix.h"
// Assume we have already opened the .mat file and read the variable into mxArray* variablePtr
// ...
mwArray mwVariable(variablePtr); // convert mxArray to mwArray
// Now we can use mwVariable in our C++ shared libraries
Note:
When you convert an mxArray to an mwArray, MATLAB creates a copy of the data. This means that if you modify the mwArray in your C++ code, the original mxArray will not be affected. If you need to modify the original data, you will need to copy the mwArray back to an mxArray when you're done.

Products


Release

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!