Transformation from matrix to array:
1 2 3 4
5 6 7 8= A[3][4] where A.lin=3 and A.col=4 so => V.elem=3*4=12
9 0 1 2
So
1 2 3 4 5 6 7 8 9 0 1 2= V.vector[12]
The formula is:
k=A.col*i+j
Transformation from array to matrix:
1 2 3 4 5 6 7 8 9 0 1 2= V.vector[12]=> V.elem=12.=>
1 2 3 4
5 6 7 8=A[3][4]
9 0 1 2
The formulas are:
i=k/A.col and j=k%A.col
And the code is:
-----------------------------------------------------------------------------------------------
def.c
typedef struct{
double **matr;
int lin;
int col;
}Matrice;
typedef struct{
double *vector;
int elem;
}Array;
int i,j,k;
Matrice A,B; Array V;
-----------------------------------------------------------------------------------------------
functii.c
// citire matrice
void citire_matr(Matrice A){
for(i=0;i<A.lin;i++)
{ for(j=0;j<A.col;j++)
scanf("%lf",&A.matr[i][j]);
}
}
//afisare matrice
void afisare_matrice(Matrice A){
for(i=0;i<A.lin;i++)
{for(j=0;j<A.col;j++)
printf("%lf ",A.matr[i][j]);
printf("
");
");
}
printf("
");
");
}
//afisare vector
void afisare_vector(Array V){
for(k=0;k<V.elem;k++)
printf("%lf ",V.vector[k]);
printf("
");
");
}
//transformare matrice->vector
void matr_vector(Matrice A, Array V){
for(i=0;i<A.lin;i++)
for(j=0;j<A.col;j++)
V.vector[A.col*i+j]=A.matr[i][j];
}
//transformare vector->matrice
void vectortomatr(Matrice B, Array V){
i=j=k=0;
while(k<V.elem){
B.matr[k/B.col][k%B.col]=V.vector[k];
i++;j++;k++;
}
}
-----------------------------------------------------------------------------------------------
main.c
#include<stdio.h>
#include<stdlib.h>
#include "def.c"
#include "functii.c"
int main(){
printf("Nr de linii si numarul de coloane este:");scanf("%d %d",&A.lin,&A.col);
V.elem=A.col*A.lin;
B.lin=A.lin; B.col=A.col;
A.matr=(double **) malloc(A.lin*sizeof(double*));
B.matr=(double **) malloc(B.lin*sizeof(double*));
V.vector=(double *)malloc(V.elem*sizeof(double));
for(i=0;i<A.lin;i++) // aloca memorie pt elem din linia i
if((A.matr[i]=(double *)malloc(A.col*sizeof(double)))==NULL || (B.matr[i]=(double *)malloc(B.col*sizeof(double)))==NULL)
{
printf("
memorie insuficienta");
memorie insuficienta");
exit(1) ;
}
else
if(V.vector==NULL)
{
printf("
memorie insuficienta");
memorie insuficienta");
exit(1) ;
}
citire_matr(A);
printf("Afisare matrice:
");
");
afisare_matrice(A);
matr_vector(A,V);
printf("Afisare vector:
");
");
afisare_vector(V);
vectortomatr(B,V);
printf("Afisare matrice:
");
");
afisare_matrice(B);
free(A.matr);
free(B.matr);
free(V.vector);
system("pause");
return 0;
}
-----------------------------------------------------------------------------------------------
0 komentar:
Posting Komentar