If you want to copy data into your matrix, you cannot do it in less than O (N) time, be it a row or column, with the exception of a small N, where hardware functions can be used.
However, if your matrices are immutable, you can use smoke and mirrors to create the illusion of having a separate column vector.
The code below is entered directly into the response text box and does not even compile. Use at your own risk!
The type of matrix is defined as a structure in this way:
typedef struct
{
unsigned int refCount;
size_t lineWidth;
double* data;
} DataRef;
typedef struct
{
size_t rows;
size_t cols;
size_t dataOffset;
DataRef* data;
} Matrix;
To create a completely new matrix (I skipped all error handling to simplify it).
Matrix* matrix_create(size_t rows, size_t cols, const double* values)
{
Matrix* ret = calloc(1, sizeof *ret);
ret->rows = rows;
ret->cols = cols;
ret->dataOffset = 0;
ret->data = calloc(1, sizeof *dataRef);
ret->data->lineWidth = cols;
ret->data->data = allocateAndCopy(rows * cols, values);
ret->data->refCount = 1;
return ret;
}
To access an element (again, there is no error handling, such as border errors)
double matrix_elementAt(Matrix* matrix, size_t row, size_t col)
{
size_t offset = matrix->dataOffset + row * matrix->data->lineWidth + col;
return *(matrix->data->data + offset);
}
To create a new matrix from a rectangular region of another matrix (again, error handling is required)
Matrix* matrix_createFromRegion(Matrix* old, size_t startRow, size_t startCol, size_t rows, size_t cols)
{
Matrix* ret = calloc(1, sizeof *ret);
ret->rows = rows;
ret->cols = cols;
ret->dataOffset = old->dataOffset + startRow * old->dataLineWidth + startCol;
ret->data = old->data;
ret->data->refCount++;
return ret;
}
:
Matrix* vector = matrix_createFromRegion(aMatrix, 0, colYouWant, matrix_numRows(aMatrix), 1);
void matrix_free(Matrix* aMatrix)
{
if (aMatrix->data->refCount == 1)
{
free(aMatrix->data->data);
free(aMatrix->data);
}
else
{
aMatrix->data->refCount--;
}
free(aMatrix);
}
, , , refCount , 1, DataRef ( refCount dataRef), dataRef .
mallocs , . , DataRef Matrix , , , . , , . , , , .