【问题标题】:Matrix multiplication with random numbers larger than 1000大于 1000 的随机数的矩阵乘法
【发布时间】:2016-02-29 10:48:02
【问题描述】:

我试图让两个具有随机生成的数字的矩阵相乘,但我不断遇到分段错误,并且不知道如何正确分配内存。

这方面的任何帮助都会很棒

//这里是代码

#include<iostream>
#include<iomanip>
#include<stdlib.h>
#include<stdio.h>
#include<ctime>

using namespace std;
int main()
{ 
srand (1023);
int a[1000][1000], b[1000][1000], mult[1000][1000], r1, c1, r2, c2, i, j, k;
cout << "Enter rows and columns for first matrix: ";
cin >> r1 >> c1;
cout << "Enter rows and columns for second matrix: ";
cin >> r2 >> c2;

while (c1!=r2)
{
   cout << "Error! column of first matrix not equal to row of second.";

}

cout << endl << endl;
for(i=0; i<r1; ++i)
for(j=0; j<c1; ++j)
{
    cout<<"mult["<<i<<"]["<<j<<"]: "<<rand()%9+1<<" "; //random matrix 1
}

cout << endl<< endl;
for(i=0; i<r2; ++i)
for(j=0; j<c2; ++j)
{
    cout<<"mult["<<i<<"]["<<j<<"]: "<<rand()%9+1<<" "; //random matrix 2
}

for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
{
   mult[i][j]=rand()%9+1;
}


for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
for(k=0; k<c1; ++k)
{
    mult[i][j]+=a[i][k]*b[k][j]; //matrix multiplication
}

cout << endl << "Output Matrix: " << endl;
clock_t begin = clock();
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
    cout << " " << mult[i][j];
    if(j==c2)
        cout << endl;
clock_t end = clock();
    double elapsed_secs = double(end-begin)*100;
    cout<<"Elapsed Time: "<<elapsed_secs<<" milliseconds\n";
return 0;
}

【问题讨论】:

  • 不要使用int,存储大量数字。
  • 您根本没有初始化数组 ab 的元素。访问它们的元素,即使使用有效的索引,也会产生未定义的行为。
  • 那么你将如何初始化它们

标签: c++ matrix matrix-multiplication


【解决方案1】:

您正在尝试在当前堆栈中创建超过 11 MB。

数组[1000][1000] = 4 * 1000 * 1000 字节 = 4000000

您仅为 3 个数组创建了总共 12000000 个字节。

尝试减小数组的大小(或)获取矩阵的大小并尝试使用 new 在堆中创建数组。

检查你的堆栈大小,应该是 8 MB

ulimit -a | grep stack

这就是你对堆的做法,因为你想要 1000 到 5000

   int** a = new int*[r1];
   for(int i = 0; i < r1; ++i)
   {
      a[i] = new int[c1];
   }

   a[0][0] = 10;

   std::cout << a[0][0] << std::endl;

   // Delete all the columns  
   for(int i = 0; i < r1; ++i)
     delete[] a[i];

   delete []a ;                     

还要确保将值添加到 a[][] 和 b[][],现在您只需执行 cout 并打印前 2 个 for 循环中的值,我想这些值应该在 a[][] 和b[][]

【讨论】:

  • 我需要数组介于 1000 到 5000 之间
  • 你可以在堆中创建。使用 new 和 delete[] 运算符在堆中创建和删除数组
  • 我尝试过这样做,我们 a[][], b[][], mult[][] 但它不起作用
  • 这是在 ubuntu 中的
  • @nathan 用如何在堆中创建二维数组的示例编辑了答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-27
  • 1970-01-01
  • 2011-05-02
  • 2013-01-11
  • 1970-01-01
相关资源
最近更新 更多