您的位置:首页 > 编程语言 > C语言/C++

矩阵直接转置和快速转置的小例子,VC++6.0通过

2010-12-17 07:37 399 查看
#include <stdio.h>
#include<stdlib.h>
#define MAXSIZE 20

typedef struct
{
int i;
int j;
int e;
}Triple;

typedef struct
{
int mu;
int nu;
int tu;
Triple data[MAXSIZE+1];
}Tabletype;

void out_matrix(Tabletype m);

void Transpose1(Tabletype a,Tabletype *b);
void Transpose2(Tabletype a,Tabletype *b);

void main()
{
Tabletype a={6,7,8,{{1,2,12,},{1,3,9},{3,1,-3},{3,6,14},{4,3,24},{5,2,18},{6,1,15},{6,4,-7}}};
Tabletype b;
printf("The original matrix is :/n");
out_matrix(a);
Transpose1(a,&b);
printf("The followed matrix is the Transpose1 of the front matrixe/n");
out_matrix(b);

Transpose2(b,&a);
printf("The followed matrix is the Transpose2 of the front matrixe/n");
out_matrix(a);

}

//输出矩阵函数
void out_matrix(Tabletype m)
{
int i,j,k;
k=0;
for (i=1;i<=m.mu;i++)
{
for (j=1;j<=m.nu;j++)
if((m.data[k].i==i)&&(m.data[k].j==j))
{
printf("%5d",m.data[k].e);
k++;
}
else
printf("%5d",0);

printf("/n");
}
}

//直接转置
void Transpose1(Tabletype a,Tabletype *b)
{
int p,q,col;
(*b).mu=a.nu;
(*b).nu=a.mu;
(*b).tu=a.tu;
if((*b).tu)
{
q=0;
for(col=1;col<=a.nu;col++)
for(p=0;p<a.tu;p++)
if(a.data[p].j==col)
{
(*b).data[q].i=a.data[p].j;
(*b).data[q].j=a.data[p].i;
(*b).data[q].e=a.data[p].e;
q++;
}
}
}

//快速转置
void Transpose2(Tabletype a,Tabletype *b)
{
int p,q,col,t;
int num[MAXSIZE+1];
int cpot[MAXSIZE+1];
(*b).mu=a.nu;
(*b).nu=a.mu;
(*b).tu=a.tu;
if((*b).tu)
{
for(col=1;col<=a.nu;col++)
num[col]=0;

for(t=0;t<a.tu;t++)
num[a.data[t].j]++;

cpot[1]=1;
for(col=2;col<=a.nu;col++)
cpot[col]=cpot[col-1]+num[col-1];

for(p=0;p<a.tu;p++)
{
col= a.data[p].j;
q=cpot[col]-1;
(*b).data[q].i=a.data[p].j;
(*b).data[q].j=a.data[p].i;
(*b).data[q].e=a.data[p].e;
cpot[col]++;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: