1

行列を転置するための次のコードがあります。

for(j=0; j<col; j++) { 
    for(k=0; k<row; k++) {
        mat2[j][k] = mat[k][j];
    }

正方行列では機能するようですが、非正方行列では機能しないようです。助けて!

4

6 に答える 6

3

非正方行列でも機能しますが、の行数がの列mat2数と一致していることを確認する必要がありますmat。その逆も同様です。つまり、が行列の場合、matNxM行列でmat2なければなりませんMxN

于 2010-08-25T17:39:25.660 に答える
2

それは、アプリケーションで使用した実際のコードですか? それは間違っているからです。ステートメント
の構文は次のとおりです。for

for (Initialization; Condition to continue with the loop; Step Operation) {}

あなたの場合、次のようなものを使用する必要があります。

#define COLS 10
#define ROWS 5

int mat[COLS][ROWS];
int mat2[ROWS][COLS];

int i, j;

for (i = 0; i < COLS; i ++) {
    for (j = 0; j < ROWS; j++) {
        mat2[j][i] = mat[i][j];
    }
}

このようにして、行列を転置できます。当然、この方法では、マトリックスの次元を事前に知る必要があります。別の方法は、次のように、ユーザーが提供するデータを使用してマトリックスを動的に初期化することです。

int ** mat;
int ** mat2;

int cols, rows;
int i, j;

/* Get matrix dimension from the user */

mat = (int **) malloc (sizeof(int *) * cols);

for (i = 0; i < cols; i++) {
    mat[i] = (int *) malloc (sizeof(int) * rows);
}

このようにして、行列を動的に初期化し、以前と同じ方法で転置できます。

于 2010-08-25T17:46:08.407 に答える
0

C ++で定義済みの次元を持つ非正方行列の転置のコードは、次のようになります。

#include <iostream>

using namespace std;

int main()
{
int a[7][6],b[6][7],x,i,j,k;
/*Input Matrix from user*/
cout<<"Enter elements for matrix A\n";
for(i=0;i<7;i++)
    {for(j=0;j<6;j++)
       {
         cin>>a[i][j];
       }
    }
 /*Print Input Matrix A*/
 cout<<"MATRIX A:-"<<endl;
 for(i=0;i<7;i++)
    {for(j=0;j<6;j++)
       {
         cout<<a[i][j];
       }
       cout<<endl;
    }
/*calculate TRANSPOSE*/
for(i=0;i<7;i++)
    {for(j=0,k=5;j<6;j++,k--)
        {
         x=j+(k-j);
         b[x][i]=a[i][j];
        }
    }
/*Print Output Matrix B*/
cout<<"matrix B:-\n";
for(i=0;i<6;i++)
  {for(j=0;j<7;j++)
   {
       cout<<b[i][j];
   }
   cout<<endl;
  }
}

適切なヘッダーと print/scan ステートメントに置き換えて、C でコードを記述し、代わりにユーザーからの入力を取得して同じものを実装することができます。

于 2013-01-10T23:25:13.717 に答える
0

col が mat2 (および mat の列) の行数であり、row が mat2 (および mat の行) の列数である場合、これは機能するはずです。

余分な閉じたカーリーが必要ですが、コードにそれがあると思います。

于 2010-08-25T17:37:45.183 に答える
0
  #include<conio.h>
  #include<ctype.h>
 #include<iostream.h>
 void trans(int [][10], int , int );
 int main()
 {
     int a[10][10],n,m,i,j;
  clrscr();
  cout<<"Enter the no. of rows and Columns: ";
  cin>>n>>m;
  cout<<"\n Enter the Matrix now:";
  for(i=0;i<n;i++)
   for(j=0;j<m;j++)
     cin>>a[i][j];  
  trans(a,n,m);
  getch();
  return 0;
 }
 void trans( int a[][10] , int n , int m )
 {  
   int i,b[10][10],j;
    for(i=0;i<n;i++)
     for(j=0;j<m;j++)
      { 
       b[j][i]=a[i][j];
      }
     cout<<"\n\nSize before Transpose "<<n<<"x"<<m<<"\n\n";
     for(i=0;i<m;i++)
       {
         for(j=0;j<n;j++)
          cout<<b[i][j]<<"\t";
     cout<<"\n";
      }
  cout<<"\n\nSize after transpose "<<m<<"x"<<n;  
   }
于 2016-06-15T14:50:00.710 に答える