V
V
vixxxen2020-06-06 12:06:26
C++ / C#
vixxxen, 2020-06-06 12:06:26

How to fix matrix multiplication code?

I can not understand what I did wrong
The code multiplies the matrix by the same transposed matrix. Works with matrix size n*m, n<=m, if n>m throws System.AccessViolationException.
I understand that the error is as stupid as possible, but I can not find it.
The code:

namespace Liba {
  public ref class Class1
  {
  public:
    static void enter_mas(int* mas, int n);
    static void Inputmas(int** a, int n, int m);
    static void Del(int** mas, int m);
    static int** TranspMatrix(int** Matrix, int n, int m);
    static int** MulMatr(int** M1, int r1, int c1, int** M2, int r2, int c2);

  };
}

void Class1::Inputmas(int** a, int n, int m) {
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        a[i][j] = 0 + (rand() % 20);
      }
    }
  
int** Class1::MulMatr(int** M1, int r1, int c1, int** M2, int r2, int c2) {
    int** MulMatr = new int* [r1];
    for (int i = 0; i < r1; i++) {
      for (int j = 0; j < c2; j++) {
        MulMatr[i] = new int[c2];
        MulMatr[i][j] = 0;
        for (int k = 0; k<c1; k++) {
          MulMatr[i][j] += M1[i][k] * M2[k][j];
        }
      }

    }
    return MulMatr;
  }
int** Class1::TranspMatrix(int** Matrix, int n, int m)
  {
    int** tMatrix = new int* [m];
    for (int i = 0; i < m; i++) {
      tMatrix[i] = new int[n];
    }

    for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++)
        tMatrix[j][i] = Matrix[i][j];
    return tMatrix;
  }


int** arr = new int* [n];
int** matr = new int* [m];
for (int i = 0; i < n; i++) {
arr[i] = new int[m];
}
for (int i = 0; i < m; i++) {
matr[i] = new int[n];
}
int** mult = new int* [n];
for (int i = 0; i < n; i++) {
mult[i] = new int[m];
}
Liba::Class1::Inputmas(arr, n, m);
matr = Liba::Class1::TranspMatrix(arr, n, m);
mult = Liba::Class1::MulMatr(arr, n, m, matr, m, n);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2020-06-06
@jcmvbkbc

The code multiplies the matrix by the same transposed matrix.

The above code almost multiplies two different matrices. If you move from a loop on j one level higher to a loop on i -- it will be good to multiply. But it probably has nothing to do with segfolt. What raises questions is that you don't check that .MulMatr[i] = new int[c2];
Works with matrix size n*m, n<=m, if n>m throws System.AccessViolationException.

Show all code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question