C++調用matlab執行個體

來源:互聯網
上載者:User

標籤:

這段代碼是C++調用matab引擎的過程,代碼的目的很簡單,在C++中建立一個vector數組,然後將這個vector數組單位化。寫這個代碼的目的是學些C++與matlab之間的資料互動,以供日後參考。

 

#include <iostream>

#include <cstdio>

#include <vector>

#include <math.h>

#include <time.h>

#include "engine.h"

#include<Eigen/Dense>

 

using namespace Eigen;

using namespace std;

 

vector<double> vecA;

void createA(int m );

 

int main()

{

    const int num = 10;

    createA( num );//建立原始矩陣vecA

 

    double * pa = new double[10];

    for( int i = 0; i < num; i++)

    {

        pa[i] = vecA[i];

    }

 

    Engine * m_engine;//matlab引擎

    m_engine = NULL;//初始化matlab引擎

 

    if((!m_engine && !(m_engine = engOpen(NULL))))// 開啟amatlab引擎,失敗則退出

    {

        return -1;

    }

    engSetVisible(m_engine,1);//設定matlab視窗在調用時的可見度,為a1時可見?

    

    //把需要計算的資料傳入matlab

    mxArray *VecA= mxCreateDoubleMatrix(10, 1, mxREAL);//建立10行1列的實數,組數群組類型是matlab特有的

    memcpy((void *) mxGetPr(VecA), (void *) pa, 10 * sizeof(double));//將C++中D的資料傳入matlab

 

    engPutVariable(m_engine, "vec", VecA);//指派陳述式,vec是matlab代碼中的輸入參數y,VecA是C++傳入的參數

 

    //buffer用來接收調試資訊,當matlab代碼有錯時,可以輸出buffer查看錯誤資訊

    char buffer[255];

    buffer[254] = ‘\0‘;

    engOutputBuffer(m_engine, buffer, 255);

      

    

    engEvalString(m_engine, "cd(‘D:\\code\\TestEigen\\Testeigen\\mat_code‘)");//開啟matlab代碼所在檔案夾,注意路徑中是雙反斜線

    engEvalString(m_engine,"normalV = normalizeVec(vec);");//這是matlab中的調用語句,注意,matlab的.m檔案名稱要與調用的函數名一致,否則會找不到要調用的函數

 

    printf("%s", buffer);//當matlab代碼出錯時,用來輸出調試資訊

      

 

    //接下來把matlab的計算結果傳回給C++

    mxArray * mvec = NULL; //同樣聲明一個matlab中的陣陣類型

    mvec = engGetVariable(m_engine, "normalV");

      

    

    double * cvec= NULL;//聲明一個C++中的指標

    cvec= (double*)mxGetData(mvec);//將matlab中的資料賦給C++中的資料

 

    for( int i = 0; i<num; i++)

    {

        cout<< cvec[i] << " ";

    }

 

    mxDestroyArray(VecA); //銷毀matlab數組

    mxDestroyArray(mvec);

 

    return 0;

    system("pause" );

}

 

void createA(int m )

{

    srand(time(NULL));

    for( int i = 0; i < m; i++ )

    {

        vecA.push_back(rand()%4 + 1);

        cout << vecA[i]<<" ";

    }

    cout <<endl<<"-----------------------"<<endl;

}

 

 

輸出結果:

 

Matlab代碼:

%功能是實現一個向量的單位化

function normalV = normalizeVec(vec)

     normalV = vec/sqrt(sum(vec.^2, 2));

end

 

出現錯誤時,看到提示資訊如下,

 

然後知道是normaozeVe函數沒定義,發現是調用語句寫錯了.

C++調用matlab執行個體

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.