IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    [原]C++调用Matlab画图 V2.0

    bendanban发表于 2016-05-03 23:06:26
    love 0

    实现功能

    通过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 to open MATLAB engine!" << std::endl;
            }
            else{
                std::cout << "MATLAB has been started successfully!" << std::endl;
            }
        }
        ~Matlab(){
            // if you are testing algorithm, you are encouraged to keep the line below bing committed.
            //engClose(_engine); _engine = NULL;
        }
    
        // line_spec : "LineStyle" + "Marker" + "Color", e.g. "-or"
        // for line
        // "LineStyle" = {"none", "-", ":", "-."}
        // "LineWidth" = 0.5
        // "Color" = {[0 0.4470 0.7410] (default) | RGB triplet | {y,m,c,r,g,b,w,k} | 'none'}
        // for Marker
        // "Marker" = {"none", "o", "+", "*", ".", "x", "s", "d", "^", "v", ">", "<", 'p', 'h'}
        // "MarkerEdgeColor" = 'auto' (default) | 'none' | RGB triplet | {y,m,c,r,g,b,w,k}
        // "MarkerFaceColor" = 'auto' (default) | 'none' | RGB triplet | {y,m,c,r,g,b,w,k}
        // "MarkerSize" = 6
        template<class TMatX = Eigen::MatrixXf, class TMatY = Eigen::MatrixXf, class TMask = Eigen::MatrixXi>
        int plot(const TMatX &X, const TMatY &Y, const TMask &mask,
            std::string nm0  = "",
            std::string nm1  = "", std::string nm2  = "",
            std::string nm3  = "", std::string nm4  = "",
            std::string nm5  = "", std::string nm6  = "",
            std::string nm7  = "", std::string nm8  = "",
            std::string nm9  = "", std::string nm10 = "",
            std::string nm11 = "", std::string nm12 = "",
            std::string nm13 = "", std::string nm14 = ""
        ){
            MatArray MX, MY, MS;
    
            MX.copy_from_eigen(X); MX.put(_engine, "MX");
            MY.copy_from_eigen(Y); MY.put(_engine, "MY");
            MS.copy_from_eigen(mask); MS.put(_engine, "MS");
            std::string plot_code = "MX(MS>0), MY(MS>0)";
            std::string code;
    
    #define EVL_CODE(_ARG0,_ARG1) code = var_plot_code(nm##_ARG0, nm##_ARG1); if(code != ""){ plot_code += ", " + code;}
            code = var_plot_code(nm0, "");
            if (code != ""){
                plot_code += ", " + code;
                EVL_CODE(1, 2);EVL_CODE(3, 4);EVL_CODE(5, 6);EVL_CODE(7, 8);EVL_CODE(9, 10);EVL_CODE(11, 12);EVL_CODE(13, 14);
            }
            else{
                EVL_CODE(0, 1);EVL_CODE(2, 3);EVL_CODE(4, 5);EVL_CODE(6, 7);EVL_CODE(8, 9);EVL_CODE(10, 11);EVL_CODE(12, 13);
            }
    #undef EVL_CODE
            plot_code = "plot(" + plot_code + ");";
            std::cout << plot_code << std::endl;
            exec(plot_code);
            return 0;
        }
    
    
        // line_spec : "LineStyle" + "Marker" + "Color", e.g. "-or"
        // for line
        // "LineStyle" = {"none", "-", ":", "-."}
        // "LineWidth" = 0.5
        // "Color" = {[0 0.4470 0.7410] (default) | RGB triplet | {y,m,c,r,g,b,w,k} | 'none'}
        // for Marker
        // "Marker" = {"none", "o", "+", "*", ".", "x", "s", "d", "^", "v", ">", "<", 'p', 'h'}
        // "MarkerEdgeColor" = 'auto' (default) | 'none' | RGB triplet | {y,m,c,r,g,b,w,k}
        // "MarkerFaceColor" = 'auto' (default) | 'none' | RGB triplet | {y,m,c,r,g,b,w,k}
        // "MarkerSize" = 6
        template<class TMatX = Eigen::MatrixXf, class TMatY = Eigen::MatrixXf>
        int plot(const TMatX &X, const TMatY &Y,
            std::string nm0  = "",
            std::string nm1  = "", std::string nm2  = "",
            std::string nm3  = "", std::string nm4  = "",
            std::string nm5  = "", std::string nm6  = "",
            std::string nm7  = "", std::string nm8  = "",
            std::string nm9  = "", std::string nm10 = "",
            std::string nm11 = "", std::string nm12 = "",
            std::string nm13 = "", std::string nm14 = ""
        ){
            MatArray MX, MY;
            MX.copy_from_eigen(X); MX.put(_engine, "MX");
            MY.copy_from_eigen(Y); MY.put(_engine, "MY");
            std::string plot_code = "MX, MY";
            std::string code;
    #define EVL_CODE(_ARG0,_ARG1) code = var_plot_code(nm##_ARG0, nm##_ARG1); if(code != ""){ plot_code += ", " + code;}
            code = var_plot_code(nm0, "");
            if (code != ""){
                plot_code += ", " + code;
                EVL_CODE(1, 2);EVL_CODE(3, 4);EVL_CODE(5, 6);EVL_CODE(7, 8);EVL_CODE(9, 10);EVL_CODE(11, 12);EVL_CODE(13, 14);
            }
            else{
                EVL_CODE(0, 1);EVL_CODE(2, 3);EVL_CODE(4, 5);EVL_CODE(6, 7);EVL_CODE(8, 9);EVL_CODE(10, 11);EVL_CODE(12, 13);
            }
    #undef EVL_CODE
            plot_code = "plot(" + plot_code + ");";
            std::cout << plot_code << std::endl;
            exec(plot_code);
            return 0;
        }
    
    #define TEMPLATE_PLOT(ARG3) \
        template<class TMatX = Eigen::MatrixXf, class TMatY = Eigen::MatrixXf> \
        int plot(const TMatX &X, const TMatY &Y, \
            ARG3 nm0 = "" , \
            std::string nm1  = "", std::string nm2  = "", \
            std::string nm3  = "", std::string nm4  = "", \
            std::string nm5  = "", std::string nm6  = "", \
            std::string nm7  = "", std::string nm8  = "",   \
            std::string nm9  = "", std::string nm10 = "",   \
            std::string nm11 = "", std::string nm12 = "",   \
            std::string nm13 = "", std::string nm14 = ""){  \
            return plot(X, Y, std::string(nm0), nm1, nm2, nm3, nm4, nm5, nm6, nm7, nm8, nm9, nm10, nm11, nm12, nm13, nm14); \
        }
    
        TEMPLATE_PLOT(char*);
        TEMPLATE_PLOT(const char*);
    #undef TEMPLATE_PLOT
    
        int exec(std::string cmd){
            return engEvalString(_engine, cmd.c_str());
        }
    
    protected:
        std::string var_plot_code(std::string nm, std::string var){
            boost::trim(nm); boost::trim(var);
            if (nm == ""){
                return "";
            }
            std::string code = "'" + nm + "'";
    
            if (var == ""){
                return (nm[0] < 'A' || nm[0] > 'Z') ? code : "";
            }
            if (nm == "LineStyle" || nm == "Marker"){ // string
                // 'LineStyle', '-'
                return code + ", '" + var + "'";
            }
            if (nm == "LineWidth" || nm == "MarkerSize"){ // positive number
                // 'LineWidth', 0.5
                return code + ",  " + var;
            }
            if (nm == "Color" || nm == "MarkerEdgeColor" || nm == "MarkerFaceColor"){
                if (var[0] == '['){
                    return code + ",  " + var;
                }
                else{
                    return code + ", '" + var + "'";
                }
            }
            return "";
        }
    
    private:
        Engine *_engine;
    };
    
    #endif

    实验测试

    测试代码:

    #include <Eigen/Eigen>
    #include "matlab.hpp"
    
    int main(int argc, char** argv){
        Matlab g_eng;   
        Eigen::ArrayXf X = Eigen::ArrayXf::LinSpaced(120, -3.1415926f*2.f, 2.f*3.1415926f);
    
        g_eng.exec("figure(1); clf;");
        g_eng.plot(X, X.sin(), "d", "MarkerFaceColor", "r");
        g_eng.exec("axis tight;");
    
        g_eng.exec("figure(2); clf;");
        g_eng.plot(X, X.cos(), X > 0, "->", "MarkerFaceColor", "r");
        g_eng.exec("axis tight;");
    
        Eigen::ArrayXXf data;
        data = data.Random(1000,2);
        g_eng.exec("figure(3); clf;");
        g_eng.plot(data.col(0), data.col(1), "o", "MarkerFaceColor", rndcolor());
        g_eng.exec("axis tight;");
    
        return EXIT_SUCCESS;
    }

    实验结果:

    这里写图片描述



沪ICP备19023445号-2号
友情链接