我有这个用于转置矩阵的代码:
for(j=0; j<col; j++) {
for(k=0; k<row; k++) {
mat2[j][k] = mat[k][j];
}
它似乎适用于方阵,但不适用于非方阵。帮我!
它适用于非方阵,但您必须确保 中的行mat2
数与 中的列数相匹配mat
,反之亦然。即,如果mat
是NxM
矩阵,则mat2
必须是MxN
矩阵。
那是您在应用程序中使用的实际代码吗?因为它是错误的。
该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);
}
这样你就可以动态地初始化一个矩阵,然后你可以像以前一样转置它。
如果 col 是 mat2 中的行数(和 mat2 中的列),row 是 mat2 中的列数(和 mat2 中的行),那么这应该有效。
你需要一个额外的紧密卷曲,但我假设你的代码中有这个。
在 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;
}
}
您可以用适当的标题和打印/扫描语句替换以用 C 编写代码,或者从用户那里获取输入并实现相同的。
#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;
}
#include<conio.h>
#include<stdio.h>
main()
int a[5][5],i,j,t;
clrscr();
for(i=1;i<=4;i++)
{
for(j=1;j<=5;j++)
scanf("%d",&a[i][j]);
}
for(i=1;i<=4;i++)
{
for(j=i;j<=5;j++)
{
if(i<=4&&j<=4)
{
t=a[j][i];
a[j][i]=a[i][j];
a[i][j]=t;
}
else
a[j][i]=a[i][j];
}
}
for(i=1;i<=5;i++)
{
for(j=1;j<=4;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
getch();
}