學習筆記-vs2017調用matlab2017b的plot函數

本文只是對文章https://www.cnblogs.com/shuqingstudy/p/10134254.html的學習筆記,謝謝作者“平常心,平常心”的分享!

最近經常採用Matlab仿真,然後C語言實現,最後需要將計算結果使用Qt的qwt或者matlab中的plot函數繪圖。

因此想借用matlab的plot函數接口,使用VS2015來編寫信號處理代碼,最後通過繪圖來驗證。

參考博客:

https://blog.csdn.net/shouzang/article/details/80795945

https://blog.csdn.net/libing403/article/details/79135220

非常感謝!

一、VS2015調用Matlab2016a進行繪圖

運行環境

Windows 7 64bit

Visual Studio Community 2015/2017

Matlab 2017b

 

1.1 檢查Matlab對C++編譯器的支持情況

打開Matlab,在命令行中輸入mex -setup,查看Matlab可識別的編譯器VC++ 2017。

以管理員身份運行命令提示符,切換到"matlab.exe"的路徑,輸入下方命令“matlab /regserver”進行註冊。

若不註冊,在使用engOpen()打開Matlab引擎會提示失敗。

二、VS配置及代碼示例

 測試Demo

#include<cstdlib>
#include <cstdio>
#include<cstring>
#include"engine.h"//在VS中調用matlab引擎

//注意:與原作者相比,這裏需要添加一下幾行代碼,
//否則鏈接時會報錯 無法解析的符號之類的錯誤
#pragma comment(lib, "libmat.lib")
#pragma comment(lib, "libeng.lib")
#pragma comment(lib, "libmx.lib")
#pragma comment(lib, "libmEx.lib")

const int BUFFER_SIZE = 1024;
char buffer[BUFFER_SIZE];
void test()
{
    //打開引擎
	Engine* ep;
    mxArray *x1 = NULL;
    mxArray *y1 = NULL;
    if ((ep = engOpen("")) == NULL)
    {
        printf("Engine Fail\n");
    }
	//
    engOutputBuffer(ep, buffer, BUFFER_SIZE);
    printf("Init Success\n");
 
    double x[5] = { 1.0, 2.5,3.7,4.4,5.1 };
    double y[5] = { 3.3,4.7,9.6,15.6,21.3 };
    x1 = mxCreateDoubleMatrix(1, 5, mxREAL);
    y1 = mxCreateDoubleMatrix(1, 5, mxREAL);
 
    memcpy((char*)mxGetPr(x1), (void *)x, 5 * sizeof(double));
    memcpy((char*)mxGetPr(y1), (void *)y, 5 * sizeof(double));
	//向matlab工作空間設置/獲取數據常用的函數
    engPutVariable(ep, "x", x1);
    engPutVariable(ep, "y", y1);
    engEvalString(ep, "plot(x,y)");
    getchar();
	//關閉引擎
    engClose(ep);
}
 
int main()
{
    test();
}

值得注意的是,由於matlab是在64位環境下安裝的,對應的庫文件也只有64位的,因此我們的vs工程是在X64平臺的。

爲Windows環境變量中的系統變量(S)path加上下面這兩項:多個路徑以“;”間隔

C:\Program Files\MATLAB\R2017b\bin 

C:\Program Files\MATLAB\R2017b\bin\win64

注意:添加路徑以後,需要重啓電腦;

在“VC++目錄”中:

“可執行文件目錄”中添加“Matlab安裝路徑\bin\win64”,(C:\Program Files\MATLAB\R2017b\bin\win64)

“包含目錄”中添加“Matlab安裝路徑\extern\include”, (C:\Program Files\MATLAB\R2017b\extern\include)

“庫目錄”中添加“Matlab安裝路徑\extern\lib\win64\microsoft” (C:\Program Files\MATLAB\R2017b\extern\lib\win64\microsoft)

在“鏈接器”-“輸入”中,“附加依賴項”中添加“libmat.lib”,“libeng.lib”,“libmx.lib”,“libmex.lib”,如下圖所示。

Demo編譯後即可調用Matlab進行畫圖。

三、引擎講解

正弦波代碼示例:

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<engine.h>
#define dataNum 100
int main()
{
    int ret = 0;
    Engine* eg = NULL;
    if (!(eg = engOpen(NULL)))
    {
        printf("Open matlab enging fail!");
        return 1;
    }
    double xtemp[dataNum] = { 0 };
    double ytemp[dataNum] = { 0 };
    for (int i = 0; i < dataNum; i++)
    {
        xtemp[i] = i * 2.0 * 3.1415926 / 100.0;
        ytemp[i] = sin(xtemp[i]);
 
    }
    mxArray *X = mxCreateDoubleMatrix(1, dataNum, mxREAL);//創建matlab存儲數據的指針
    mxArray *Y = mxCreateDoubleMatrix(1, dataNum, mxREAL);
 
    memcpy(mxGetPr(X), xtemp, dataNum * sizeof(double)); //數據複製
    memcpy(mxGetPr(Y), ytemp, dataNum * sizeof(double));
 
    if ((ret = engPutVariable(eg, "X", X)) != 0)   //把數據傳遞到matlab工作空間,並命名爲X
        printf("engPutVariable error:%d\n", ret);
    if ((ret = engPutVariable(eg, "Y", Y)) != 0)
        printf("engPutVariable error:%d\n", ret);
    engEvalString(eg, "plot(X,Y)");//運行繪圖命令
    getchar();
    if(eg)
        engClose(eg);
    return 0;
}

編寫matlab命令封裝函數
從上面的編程可以看出,調用matlab進行繪圖過程也顯得比較繁瑣,例如要創建變量,複製內存數據,運行命令表達式等一系列操作。爲了像在matlab中一樣調用運行matlab命令的體驗,可以把matlab的命令封裝成c語言的函數。例如,下面是對plot命令的封裝:

#include<stdio.h>
#include<engine.h>//在VS中調用matlab引擎

#include<string.h>
#include<math.h>
#define dataNum 100
 
//忽略4096錯誤
#pragma warning(disable:4996)

//否則鏈接時會報錯 無法解析的符號之類的錯誤
#pragma comment(lib, "libmat.lib")
#pragma comment(lib, "libeng.lib")
#pragma comment(lib, "libmx.lib")
#pragma comment(lib, "libmEx.lib")

int mat_plot(Engine *eg, double *x, double *y, int N, char *LineStyle, double LineWidth, double MarkerSize)
{
    int ret = 0;
    mxArray *X = mxCreateDoubleMatrix(1, N, mxREAL);
    mxArray *Y = mxCreateDoubleMatrix(1, N, mxREAL);
    mxArray *MS = mxCreateDoubleScalar(MarkerSize);
    memcpy(mxGetPr(X), x, N * sizeof(double));
    memcpy(mxGetPr(Y), y, N * sizeof(double));
 
    if ((ret = engPutVariable(eg, "X", X)) != 0)
        printf("engPutVariable error:%d\n", ret);
    if ((ret = engPutVariable(eg, "Y", Y)) != 0)
        printf("engPutVariable error:%d\n", ret);
 
    //gennerate the plot command
    char plotCommand[256] = "fig=plot(X,Y,'";
    //set line style and marker
    if (strlen(LineStyle) > 0)
        strncat(plotCommand, LineStyle, strlen(LineStyle));
    else
    {
        strncat(plotCommand, "-", strlen("-"));
    }
    strncat(plotCommand, "',", strlen(LineStyle));
 
    char temp[20] = "";
    //set line width
    if (LineWidth < 1.0)
        LineWidth = 1.0;
    strncat(plotCommand, "'LineWidth',", strlen("'LineWidth',"));
    memset(temp, 0, sizeof(temp));
    sprintf(temp, "%f,", LineWidth);
    strncat(plotCommand, temp, strlen(temp));
 
    //set marker size
    strncat(plotCommand, "'MarkerSize',", strlen("'MarkerSize',"));
    sprintf(temp, "%f", MarkerSize);
    strncat(plotCommand, temp, strlen(temp));
    strncat(plotCommand, ");", strlen(temp));
 
    //plot
    if ((ret = engEvalString(eg, plotCommand)) != 0)
    {
        printf("\nplot Command error:%s\n", plotCommand);
        return ret;
    }
    engEvalString(eg, "set(gcf,'color','w');");
    printf("plot Command ok:%s\n", plotCommand);
    //destroy mxArray,but they are still in matlab workspace
    mxDestroyArray(X);
    mxDestroyArray(Y);
    return 0;
}
 
int main()
{
    Engine* eg = NULL;
    if (!(eg = engOpen(NULL)))
    {
        printf("Open matlab enging fail!");
        return 1;
    }
 
    int ret = 0;
 
    double xtemp[dataNum] = { 0 };
    double ytemp[dataNum] = { 0 };
    for (int i = 0; i < dataNum; i++)
    {
        xtemp[i] = i * 2.0 * 3.1415926 / 100.0;
        ytemp[i] = sin(xtemp[i]);
 
    }
    mat_plot(eg, xtemp, ytemp, dataNum, "-r", 1, 5);
 
    getchar();
    if (eg)
        engClose(eg);
    return 0;
}

這樣使用起matlab命令就方便多了,例如我要用c語言裏運算的數據來畫圖,直接調用封裝的函數就可以了

mat_plot(eg, xtemp, ytemp, dataNum, "-r", 1, 5);

上面參數含義

eg:指向打開的matlab引擎指針

xtemp:x座標數據

ytemp:y軸座標數據

dataNum:數據個數

“-r”:線型,顏色(還可以設置標記例如“–r*”)

1:線寬

5:標記大小

這樣就不用關心數據是怎樣傳遞數據到matlab和怎樣運行畫圖命令的。封裝函數寫得好些,就可以像matlab裏面使用更像,例如直接設置線型,線寬。

四、小結
以前對c算法進行測試時,需要把c產生的數據導數到matlab,再進行繪圖,看效果。這樣既要寫c語言程序,還得專門寫matlab程序進行測試,而且要繪製動態圖形就特別麻煩。現在這樣通過直接在c/c++調用matlab引擎進行數據可視化處理,可以在C語言環境裏,調用matlab幾乎所有命令。要是把matlab命令封裝好,就跟在matlab裏畫圖一樣方便,可以極大提高開發效率。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章