1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <string.h>
double **creerMat(int nlignes, int ncolonnes)
{
double **m = malloc(nlignes * sizeof *m);
/* -tc- Attention, il faut toujours tester la validite de l'adresse
retournee par malloc() */
if (m != NULL)
{
for (int i=0 ; i < nlignes; i++)
{
m[i] = malloc(ncolonnes * sizeof *m[i]);
if (m[i] != NULL)
{
/* -tc- Tout est OK, on peut eventuellement initialliser
la matrice */
}
else
{
/* -tc- Echec d'allocation: il faut faire le menage */
do
{
free(m[i]);
}
while (i-- > 0);
free(m), m = NULL;
}
}
}
else
{
/* -tc- Ici, m vaut NULL. On retourne cette valeur telle quelle */
}
return m;
}
void libererMat(double **m, int nlignes)
{
for(int i=0 ; i < nlignes ; i++)
{
free(m[i]);
}
free(m);
}
double **trMat(double **m, int l, int c)
{
double **tr_m = creerMat(c,l);
/* -tc- Toujours verifier la validite de l'adresse d'une fonction qui
realise une allocation dynamique de memoire */
if (tr_m != NULL)
{
for (int i = 0; i < l; i++)
{
for (int j = 0; j < c; j++)
{
tr_m[j][i] = m[i][j];
}
}
}
return tr_m;
}
double **prodMat(double **A, int l, int c, double **B, int t)
{
double **pr = creerMat(l,t);
if (pr != NULL)
{
for (int i = 0 ; i < l; i++)
{
/* -tc Attention, la condition d'arret est j < t et non j < c */
for (int j = 0 ; j < t; j++)
{
pr[i][j] = 0;
for (int k = 0 ; k < c; k++)
{
pr[i][j] += A[i][k] * B[k][j];
}
}
}
}
return pr;
}
double **absMat(double **m, int l, int c)
{
double **abs_m = creerMat(l, c);
if (abs_m != NULL)
{
for (int i = 0 ; i < l ; i++)
{
for (int j = 0 ; j < c ; j++)
{
abs_m[i][j] = fabs(m[i][j]);
}
}
}
return abs_m;
}
double **test(double **A, int l, int c, double **s)
{
double **tr_s = NULL;
double **m = NULL;
double **abs_m = NULL;
tr_s = trMat(s, 1, c);
m = prodMat(A, l, c, tr_s, 1);
libererMat(tr_s, l), tr_s = NULL;
abs_m = absMat(m, l, 1);
libererMat(m, l), m = NULL;
return abs_m;
}
int main()
{
double **A = creerMat(3,2);
double **s = creerMat(1,2);
int l = 3 ;
int c = 2;
A[0][0] = 4;
A[0][1] = 2;
A[1][0] = 7;
A[1][1] = 1;
A[2][0] = 3;
A[2][1] = 5;
s[0][0] = 1;
s[0][1] = 6;
double **res = test(A, l, c, s);
libererMat(A, l);
libererMat(s, 1);
libererMat(res, l);
return EXIT_SUCCESS;
} |
Partager