在C ++中将两个矩阵相乘 [英] Multiply two matrices in C++

查看:74
本文介绍了在C ++中将两个矩阵相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,该程序接受两个不同矩阵的元素,然后将它们相乘,然后将其保存在多维数组中。
但是它仅适用于方矩阵。 (Visual Studio 2013没有错误。)
如果您帮助我编辑此代码以乘以每种矩阵,我将感到高兴。

I'm writing a program which takes the elements of two different matrices, then it will multiply them and next it will save them in a multidimensional array. But it only works for square matrix. (Visual Studio 2013 gives no error.) I'll be pleased if you help me edit this code in order to multiply every kind of matrix.

    int a, b, c, d;
    int Mat1[10][10];
    int Mat2[10][10];
    int Mat3[10][10];
    Back1:
    cout << endl << "Enter the number of rows in Matrix 1 : ";
    cin >> a;
    cout << endl << "Enter the number of columns in Matrix 1 : ";
    cin >> b;
    cout << endl << "Enter the number of rows in Matrix 2 : ";
    cin >> c;
    cout << endl << "Enter the number of column in Matrix 2 : ";
    cin >> d;
    if (b != c) {
        cout << endl << "******************************************"
             << "\nThis type of Matrix can't be multiplied . " << endl;
        goto Back1;
    }
    for (int i = 0; i < a; i++) {
        for (int j = 0; j < b; j++) {
            cout << endl << "(MAT 1 ) \n\nEnter the Element of row " << i + 1
                 << " column " << j + 1 << " : ";
            cin >> Mat1[i][j];
        }
    }
    for (int i = 0; i < c; i++) {
        for (int j = 0; j < d; j++) {
            cout << endl << "(MAT 2 ) \n\nEnter the Element of row " << i + 1
                 << " column " << j + 1 << " : ";
            cin >> Mat2[i][j];
        }
    }
    for (int i = 0; i < a; i++) {
        for (int j = 0; j < d; j++) {
            Mat3[i][j] = Mat1[i][j] * Mat1[i][j];
        }
    }
    for (int i = 0; i < a; i++) {
        for (int j = 0; j < d; j++) {
            cout << setw(4) << Mat3[i][j] << setw(4);
        }
        cout << endl;
    }
}


推荐答案

您的矩阵乘法的代码是错误的。代替:

Your code for multiplication of the matrices is wrong. Instead of:

for (int i = 0; i < a; i++)
{
   for (int j = 0; j < d; j++)
   {
      Mat3[i][j] = Mat1[i][j] * Mat1[i][j];
   }
}

您需要:

for (int i = 0; i < a; i++)
{
   for (int j = 0; j < d; j++)
   {
      Mat3[i][j] = 0;
      for (int k = 0; k < c; k++)
      {
         Mat3[i][j] += Mat1[i][k] * Mat2[k][j];
      }
   }
}

这篇关于在C ++中将两个矩阵相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆