实现功能
通过C++调用Matlab的接口来实现plot的部分功能。
程序依赖
代码依赖:Matlab,Eigen,Boost
测试版本:Matlab2015B,Eigen3.2.8,Boost1.57.0
适合人群:代码发烧友
程序代码
代码1:matlab.hpp
#ifndef __MATLAB_HPP__
#define __MATLAB_HPP__
#include <engine.h>
#include <string>
#include <iostream>
#include <boost\algorithm\string.hpp>
std::string rndcolor(){
std::string color = "[";
color += std::to_string((rand() % 256) / 255.) + ",";
color += std::to_string((rand() % 256) / 255.) + ",";
color += std::to_string((rand() % 256) / 255.) + "]";
return color;
}
class MatArray
{
public:
MatArray() : _data(NULL){}
MatArray(size_t irows, size_t icols){
resize(irows, icols);
}
MatArray(const MatArray &obj){
if (obj._data){
_data = mxCreateDoubleMatrix(obj.rows(), obj.cols(), mxREAL);
memcpy(this->ptr(), obj.ptr(), sizeof(double)*rows()*cols());
}
else{
_data = NULL;
}
}
~MatArray(){ mxDestroyArray(_data); _data = NULL; }
inline size_t rows() const { return _data ? mxGetM(_data) : 0; }
inline size_t cols() const { return _data ? mxGetN(_data) : 0; }
inline double* ptr() const { return _data ? mxGetPr(_data) : NULL; }
bool resize(size_t irows, size_t icols){
if (!_data){
_data = mxCreateDoubleMatrix(irows, icols, mxREAL);
return (_data != NULL);
}
if (rows() == irows || cols() == icols){
return true;
}
mxDestroyArray(_data);
_data = mxCreateDoubleMatrix(irows, icols, mxREAL);
return (_data != NULL);
}
int put(Engine *ep, const char* var_name){
return engPutVariable(ep, var_name, _data);
}
template<class EigenMat = Eigen::MatrixXf>
void copy_from_eigen(const EigenMat &emat){
if (emat.rows()*emat.cols() == 0){
mxDestroyArray(_data); _data = NULL;
}
resize(emat.rows(), emat.cols());
for (int c = 0; c < emat.cols(); c++){
for (int r = 0; r < emat.rows(); r++){
(*this)[r + c*(int)(emat.rows())] = emat(r, c);
}
}
}
inline double& operator[](int i){
return ptr()[i];
}
private:
mxArray *_data;
};
class Matlab
{
private:
Matlab(const Matlab &obj){}
public:
Matlab(){
_engine = engOpen(NULL);
if (!_engine){
std::cerr << "failed