RoboidControl-cpp/Matrix.cpp
2024-02-14 10:37:20 +01:00

60 lines
1.8 KiB
C++

#include "Matrix.h"
template <>
void MatrixOf<float>::Transpose(MatrixOf<float>* r) {
// Check dimensions first
// We dont care about the rows and cols (we overwrite them)
// but the data size should be equal to avoid problems
// We cannot check the data size directly, but the row*col should be equal
int matrixSize = this->cols * this->rows;
if (matrixSize != r->rows * r->cols)
// Exception??? For now we don't do anything
return;
r->cols = this->rows;
r->rows = this->cols;
for (int rDataIx = 0; rDataIx < matrixSize; rDataIx++) {
int rowIx = rDataIx / this->rows;
int colIx = rDataIx % this->rows;
int mDataIx = this->cols * colIx + rowIx;
r->data[rDataIx] = this->data[mDataIx];
}
}
template <>
void MatrixOf<float>::Multiply(MatrixOf<float>* m1,
MatrixOf<float>* m2,
MatrixOf<float>* r) {
for (int rowIx1 = 0; rowIx1 < m1->rows; rowIx1++) {
for (int colIx2 = 0; colIx2 < m2->cols; colIx2++) {
int rDataIx = colIx2 * m2->cols + rowIx1;
r->data[rDataIx] = 0.0F;
for (int kIx = 0; kIx < m2->rows; kIx++) {
int dataIx1 = rowIx1 * m1->cols + kIx;
int dataIx2 = kIx * m2->cols + colIx2;
r->data[rDataIx] += m1->data[dataIx1] * m2->data[dataIx2];
}
}
}
}
template <>
void MatrixOf<float>::Multiply(MatrixOf<float>* m2, MatrixOf<float>* r) {
Multiply(this, m2, r);
}
template <>
Vector3 MatrixOf<float>::Multiply(MatrixOf<float>* m, Vector3 v) {
float* vData = new float[3]{v.x, v.y, v.z};
MatrixOf<float> v_m = MatrixOf<float>(3, 1, vData);
float* rData = new float[3]{};
MatrixOf<float> r_m = MatrixOf<float>(3, 1, rData);
Multiply(m, &v_m, &r_m);
Vector3 r = Vector3(r_m.data[0], r_m.data[1], r_m.data[2]);
delete[] vData;
delete[] rData;
return r;
}