C++ MATLAB Data API를 사용하여 배열 만들기
배열 만들기
C++ MATLAB® Data API를 사용하면 MATLAB 외부에서 실행되는 애플리케이션이 MATLAB에 종속되지 않는 중립적인 인터페이스를 사용하여 MATLAB 데이터를 처리할 수 있습니다. API는 최신 C++ 의미 체계와 설계 패턴을 사용하며, 가능한 경우 항상 MATLAB 쓰기 시 복사(copy-on-write) 의미 체계를 사용하여 데이터 복사를 피합니다.
MATLAB Data API의 헤더 파일은 MatlabDataArray.hpp입니다.
matlab::data::Array 클래스는 모든 배열 유형의 기본 클래스입니다. 이는 유형 및 크기와 같은 일반적인 배열 정보를 제공합니다. Array 클래스는 1차원 배열 및 다차원 배열을 모두 지원합니다. MATLAB Data API는 0부터 시작하는 인덱싱 방식을 사용합니다.
배열을 만들기 위해 먼저 matlab::data::ArrayFactory를 사용하여 팩토리를 만듭니다.
matlab::data::ArrayFactory factory;
팩토리를 사용하여 double형의 2×2 배열을 만듭니다. MATLAB 명령문 A = [1 2; 3 4]의 순서와 일치하도록 열 우선(Column-major) 형식으로 배열 값을 지정합니다. 배열을 검사하려면 matlab::data::Array 클래스에 함수를 사용하십시오.
#include "MatlabDataArray.hpp"
int main() {
using namespace matlab::data;
ArrayFactory factory;
Array A = factory.createArray<double>({ 2,2 },
{ 1.0, 3.0, 2.0, 4.0 });
// Inspect array
ArrayType c = A.getType();
ArrayDimensions d = A.getDimensions();
size_t n = A.getNumberOfElements();
return 0;
}이 코드는 다음 MATLAB 명령문과 동일합니다.
A = [1 2; 3 4]; c = class(A); d = size(A); n = numel(A);
matlab::data::TypedArray 클래스는 이터레이터를 지원하며, 이를 통해 범위 기반 for 루프를 사용할 수 있습니다. 이 예제에서는 3×2 TypedArray로부터 1×6 배열을 만듭니다.
#include "MatlabDataArray.hpp"
int main() {
using namespace matlab::data;
ArrayFactory factory;
// Create a 3-by-2 TypedArray
TypedArray<double> A = factory.createArray( {3,2},
{1.1, 2.2, 3.3, 4.4, 5.5, 6.6 });
// Assign values of A to the double array C
double C[6];
int i = 0;
for (auto e : A) {
C[i++] = e;
}
return 0;
}행 우선 데이터에서 열 우선 배열 만들기
행 우선 순서의 데이터로 생성된 std::vector가 있는 경우 MATLAB에서 이 데이터로 열 우선 TypedArray를 만들 수 있습니다.
#include "MatlabDataArray.hpp"
int main() {
using namespace matlab::data;
ArrayFactory factory;
const std::vector<double> data{1, 2, 3, 4, 5, 6};
// Create a 2-by-3 TypedArray in column-major order
TypedArray<double> A = factory.createArray( {2,3},
data.begin(), data.end(), InputLayout::ROW_MAJOR);
// Assign values of A to the double array C
double C[6];
int i = 0;
for (auto e : A) {
C[i++] = e;
}
return 0;
}배열에 포함된 각 요소에 대해 연산 수행하기
요소에 대한 참조를 사용하여 matlab::data::Array에서 각 요소를 수정할 수 있습니다. 이 예제에서는 matlab::data::TypedArray의 각 요소와 스칼라 값을 곱합니다.
#include "MatlabDataArray.hpp"
int main() {
using namespace matlab::data;
ArrayFactory factory;
// Create a 3-by-2 TypedArray
TypedArray<double> A = factory.createArray( {3,2},
{1.1, 2.2, 3.3, 4.4, 5.5, 6.6 });
// Define scalar multiplier
double multiplier(10.2);
// Multiple each element in A
for (auto& elem : A) {
elem *= multiplier;
}
return 0;
}