0

I have written a matrix class and have a problem with multiplication. I want multiply only square matrices and have no idea how to handle it. Can anybody help? Some code below:

//mSize - matrix size, mP - matrix pointer
int mSize, *mP;

//constructor
matrix(){
    mP = NULL;
    mSize = 0;
}

 matrix operator*(const matrix & mat){
    matrix mul;
    mul.mSize = mat.mSize;
    mul.mP = new int[mul.mSize * mul.mSize];
    if(mSize == mat.mSize){
        for(int i = 0; i < mul.mSize * mul.mSize; i++){
            for(int j = 0; j < mul.mSize * mul.mSize; j++){
                for(int k = 0; k < mul.mSize * mul.mSize; k++){
                    mul.mP[i*j] += mP[i*k] * mat.mP[k*j];  <-- that line is not good but I don't know if only that
                }
            }
        }
    }else {
        cout << "error";
        exit(-1);
    }
    return mul;
}
  • Check the upper limits in your nested loops. The multiply operator should verify that the columns of the left-hand operand match the rows of the right-hand operand. Have a look at related posts like [this one](https://stackoverflow.com/questions/12788097/own-matrix-class-multiply-operator) – Axel Kemper May 04 '18 at 15:02

1 Answers1

0
def matrixmulti(a,b):
    if len(a[0])==len(b):                          #check it
        result=[[]*len(a) for i in range(len(b))]  #create empty matrix
        value=0
        for i in range(len(a)):                    #row of the a
            for j in range(len(b[0])):             #column of the b
                for k in range(len(b)):            #row of the b 
                    value+=a[i][k]*b[k][j]
                result[i].append(value)
                value=0
        return result
    else:
        return False

a=[[1,2],
   [3,4]]

b=[[5,6],
   [7,8]]

print(matrixmulti(a,b))

it's a python code and working wrong if not the square matrix. I hope it solves your problem. I hope you understand the code.

marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388