问题
I have a program that processes 2D array of doubles at several stages. I want to compare its results with MATLAB. I can perhaps use std::cout to print some of 8x8 size blocks the 2D array before and after processing (the algorithm works on blocks) onto the console and then manually type those numbers into MATLAB. But that is error prone and tedius. Is there a way to conviniently get this data into MATLAB?
Matlab has built in functions to simplify many things. I want to get the data before and after processing in the C++ program into MATLAB and then run some checks on it e.g draw graphs and stuff. How do I get the data from the C++ program into MATLAB?
回答1:
Have you considered using mex functions? If you do use them, I highly recommend using the Armadillo library, which provides convenient data types and methods to switch between MATLAB and C++.
For example,
#include "mex.h"
#include <armadillo>
#include "armaMex.hpp"
#include <sstream>
// gateway function
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// get data from MATLAB
mat X = conv_to<mat>::from(armaGetPr(prhs[0],true));
mat Y = conv_to<mat>::from(armaGetPr(prhs[1],true));
// do some stuff
mat Z = X + Y;
// Print data in matlab
std::ostringstream buffer;
buffer << "X = " << X << endl;
buffer << "Y = " << Y << endl;
buffer << "Z = " << Z << endl;
mexPrintf("%s", buffer.str().c_str());
// send data back to Matlab
plhs[0] = armaCreateMxMatrix(Z.n_rows, Z.n_cols, mxDOUBLE_CLASS, mxREAL);
armaSetPr(plhs[0], conv_to<mat>::from(Z));
return;
}
回答2:
It's very easy to get numerical data from a C++ program to Matlab. Just output numbers as ascii text to a file then read it in using load
Separate each number in a column by a space and each row by a newline.
Let's take a 3 rows of 2 numbers as an example and say you create a file "text.txt" that looks like this:
1 2
3 4
5 6
Then, in Matlab, the command:
load text.txt
will read the data into a variable named text
that is a 3x2 matrix.
回答3:
In addition, you could do a little bit of pretty outputting and directly write to a runnable .m
file (I use this approach to get numerics into LaTeX documents). A benefit of this approach is that you could define multiple MATLAB variables with a single file. For example:
#include <fstream>
int main() {
std::ofstream file;
file.open ("cpp_output.m");
file << "out = [\n";
for (double x = 1; x<6; x++) {
file << x << ' ' << 1/(x*x) << '\n';
}
file << "];";
file.close();
}
produces the file cpp_output.m
out = [
1 1
2 0.25
3 0.111111
4 0.0625
5 0.04
];
You probably want to change the precision (e.g. How do I print a double value with full precision using cout?)
来源:https://stackoverflow.com/questions/43903860/how-to-compare-results-between-c-and-matlab