C++调用Matlab画图 V2.0

本文介绍如何利用C++借助Matlab接口实现plot功能。内容包括程序依赖(Matlab, Eigen, Boost),适合熟悉这些工具的代码爱好者。提供了相关代码示例并展示实验结果。" 105597099,8204070,Android实现圆角EditText与光标右移技巧,"['Android开发', 'UI设计', 'EditText']
摘要由CSDN通过智能技术生成

实现功能

通过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
  • 5
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值