Create a class Matrix to store a m x n matrix. Include necessary constructors and functions to initialize and display the matrix. Using friend function, find the dot product of two input matrices.
#include <iostream>
#include <cstdlib>
using namespace std;
class Matrix {
public:
Matrix(int m, int n);
~Matrix();
void setData(double val[]);
void print();
private:
int m, n;
double *values;
double **rows;
friend
Matrix dotProduct(const Matrix& A, const Matrix& B);
};
Matrix::Matrix(int m, int n) : m(m), n(n)
{
values = new double[m*n];
rows = new double*[m];
for (int i=0; i<m; i++) {
rows[i] = values + n*i;
}
}
Matrix::~Matrix() {
delete[] rows;
delete[] values;
}
void Matrix::setData(double val[])
{
for (int i=0; i<m*n; i++) {
values[i] = val[i];
}
}
void Matrix::print()
{
for (int i=0; i<m; i++) {
for (int j=0; j<n; j++) {
cout << rows[i][j] << " ";
}
cout << endl;
}
}
Matrix dotProduct(const Matrix& A, const Matrix& B)
{
if (A.n != B.m) {
cerr << "Error: inconsistent matixes" << endl;
exit(1);
}
Matrix C(A.m, B.n);
for (int i=0; i<A.m; i++) {
for (int j=0; j<B.n; j++) {
C.rows[i][j] = 0.0;
for (int k=0; k<A.n; k++) {
C.rows[i][j] += A.rows[i][k] * B.rows[k][j];
}
}
}
return C;
}
int main()
{
Matrix A(3, 2);
double v1[] = {1, 2, 3, 1, 2, 3};
A.setData(v1);
Matrix B(2, 3);
double v2[] = {1, 0, 0, 1, 1, 2};
B.setData(v2);
Matrix C = dotProduct(A, B);
cout << "Matrix A is:" << endl;
A.print();
cout << endl << "Matrix B is:" << endl;
B.print();
cout << endl << "C = A * B is:" << endl;
C.print();
}
Comments
Leave a comment