Matrix
Matrix is a one-dimensional array with column major. This section describes how to create, access, and modify matrices, along with examples.
Creating Matrices
Use the function createMatrix
defined in the header
<Util.h>. The following is the syntax to declare a matrix:
static Vector* createMatrix(DATA_TYPE type, int cols, int rows, int colCapacity, int extraParam = 0, void* data = 0, bool containNull = false);
Arguments
- type: The data type for the elements of the created matrix, such as DT_INT, DT_DATE, etc.
- cols: The number of columns of the matrix.
- rows: The number of rows of the matrix.
- colCapacity: The amount of memory (in terms of the number of columns) allocated to the matrix.
- extraParam: It determines the scale for values in a matrix of DECIMAL type.
- data: A pointer variable that stores the address of elements to be passed
in when cols * rows is specified. When the matrix object is being
destructed,the memory block pointed by the pointer will be automatically
destroyed through
delete[]
. - containNull: It determines if any of the first cols * rows elements in the matrix contain Null values. Set to true if contains Nulls, otherwise false.
Examples
int* pData = new int[9]{1, 2, 3, 4, 5, 6, 7, 8, 9};
ConstantSP matrix = Util::createMatrix(DT_INT, 3, 3, 9, 0, pData);
std::cout << matrix->getString() << std::endl;
Output:
#0 #1 #2
-- -- --
1 4 7
2 5 8
3 6 9
Operations on Matrices
Listed below are some commonly utilized functions for operations on
matrices:
ConstantSP getRow(INDEX index) const; //return the 'index' (starts at 0) row
ConstantSP getColumn(INDEX index) const; //return the 'index' (starts at 0) column
ConstantSP get(INDEX column, INDEX row) const; //return the element at column 'column' and row 'row'
bool set(INDEX column, INDEX row, const ConstantSP& value); //set the element at column 'column' and row 'row' to 'value'
Examples
std::cout << matrix->getRow(1)->getString() << std::endl; //[2, 5, 8]
std::cout << matrix->getColumn(1)->getString() << std::endl; //[4, 5, 6]
std::cout << matrix->get(2, 2)->getString() << std::endl; //9
matrix->set(0, 0, new Int(100)); //Set the element at row 1 and column 1 to 100