Main Content

C++에서 MATLAB으로 변수 전달하기

변수를 전달하는 방법

다음과 같은 방법을 사용하여 C++ 변수를 MATLAB®으로 전달할 수 있습니다.

  • matlab::engine::MATLABEngine feval 또는 fevalAsync 멤버 함수에 대한 호출에서 함수 인수로 변수를 전달합니다. 함수 호출에 대한 인수로 전달된 변수는 MATLAB 기본 작업 공간에 저장되지 않습니다. 자세한 내용은 C++에서 MATLAB 함수 호출하기 항목을 참조하십시오.

  • matlab::engine::MATLABEngine setVariablesetVariableAsync 멤버 함수를 사용하여 MATLAB 기본 작업 공간 또는 전역 작업 공간에 변수를 넣습니다. MATLAB에서 전역 변수를 사용하는 방법에 대한 자세한 내용은 MATLAB global 함수를 참조하십시오.

matlab::engine::MATLABEngine evalevalAsync 멤버 함수를 사용하여 MATLAB 작업 공간에서 변수를 생성할 수 있습니다. 이러한 함수를 사용하여 변수에 값을 할당하는 MATLAB 명령문을 실행할 수 있습니다. 자세한 내용은 Evaluate MATLAB Statements from C++ 항목을 참조하십시오.

MATLAB 기본 작업 공간에 변수 넣기

이 샘플 코드에서는 다음 단계를 수행합니다.

  • MATLABEngine::setVariable을 사용하여 MATLAB 작업 공간에 변수를 넣습니다.

  • 이러한 변수를 사용해 MATLABEngine::eval을 이용하여 MATLAB movsum 함수를 호출합니다.

  • MATLABEngine::getVariable을 사용하여 MATLAB 작업 공간에서 출력 변수 A를 가져옵니다.

다음은 이와 동일한 MATLAB 코드입니다.

A = movsum([4 8 6 -1 -2 -3 -1 3 4 5],3,'Endpoints','discard');

다음은 C++ 코드입니다.

#include "MatlabDataArray.hpp"
#include "MatlabEngine.hpp"
#include <iostream>
void callputVariables() {
    using namespace matlab::engine;

    // Start MATLAB engine synchronously
    std::unique_ptr<MATLABEngine> matlabPtr = startMATLAB();

    //Create MATLAB data array factory
    matlab::data::ArrayFactory factory;

    // Create variables    
    matlab::data::TypedArray<double> data = factory.createArray<double>({ 1, 10 },
        { 4, 8, 6, -1, -2, -3, -1, 3, 4, 5 });
    matlab::data::TypedArray<int32_t>  windowLength = factory.createScalar<int32_t>(3);
    matlab::data::CharArray name = factory.createCharArray("Endpoints");
    matlab::data::CharArray value = factory.createCharArray("discard");
      
    // Put variables in the MATLAB workspace
    matlabPtr->setVariable(u"data", std::move(data));
    matlabPtr->setVariable(u"w", std::move(windowLength));
    matlabPtr->setVariable(u"n", std::move(name));
    matlabPtr->setVariable(u"v", std::move(value));

    // Call the MATLAB movsum function
    matlabPtr->eval(u"A = movsum(data, w, n, v);");

    // Get the result
    matlab::data::TypedArray<double> const A = matlabPtr->getVariable(u"A");
      
    // Display the result
    int i = 0;
    for (auto r : A) {
        std::cout << "results[" << i << "] = " << r << std::endl;
        ++i;
    }
}

C++ 엔진 프로그램을 설정하고 빌드하는 방법에 관한 자세한 내용은 C++ 엔진 프로그램 빌드를 위한 요구 사항 항목을 참조하십시오.

참고 항목

|

관련 항목