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
|
#include "matrici.h"
//costruttore
matrice::matrice(){
r = 0;
c = 0;
}
//distruttore
matrice::~matrice(){
}
//creazione matrice
void matrice::create(int r, int c){ // r = righe, c = colonne
int x,y;
this->r = r;
this->c = c;
m = new double *[r];
for(x=0;x<r;x++)
m[x] = new double[c];
}
void matrice::create_with_value(int r, int c, double value){
int x,y;
this->r = r;
this->c = c;
m = new double *[r];
for(x=0;x<r;x++)
m[x] = new double[c];
for(x=0;x<r;x++)
for(x=0;x<r;x++)
m[x][y] = value;
}
//visualizza matrice
void matrice::print(){
int x,y;
for(x=0;x<r;x++){
for(y=0;y<c;y++)
printf("%12.6f\x20",m[x][y]);
printf("\n");
}
printf("\n");
}
//caricamento - salvataggio matrici
void matrice::load_from_file(char * file){
FILE *stream;
char *buffer, *number;
long filesize, readed;
long x, y=0, mr=0, mc=0, r=0, c=0;
stream = fopen(file,"rb");
fseek(stream,0,SEEK_END);
filesize = ftell(stream);
rewind(stream);
buffer = (char *) malloc(filesize * sizeof(char));
number = (char *) malloc(100 * sizeof(char));
readed = fread(buffer,1,filesize,stream);
for(x=0; x<filesize ;x++){ //conta colonne
if(buffer[x] == '\x09')
mc++;
if(buffer[x] == '\x0D'){
mc++;
break;
}
}
for(x=0; x<filesize ;x++){ //conta righe
if(buffer[x] == '\x0D')
mr++;
}
create(mr, mc);
for(x=0; x<filesize ;x++){
if(buffer[x] == '\x0A')
continue;
if(buffer[x] == '\x09' || buffer[x] == '\x0D'){
number[y] = '\x00';
this->m[r][c] = atof(number);
y=0;
c++;
if(buffer[x] == '\x0D'){
r++;
c=0;
}
}
else{
number[y] = buffer[x];
y++;
}
}
}
void matrice::save_in_file(char * file){
int x,y;
FILE * stream;
stream = fopen(file, "w+");
for(x=0;x<r;x++){
for(y=0;y<c;y++){
fprintf(stream,"%.6f",m[x][y]);
if(y<c-1) fprintf(stream,"\x09");
}
fprintf(stream,"\n");
}
fclose(stream);
}
//operazioni su matrici
matrice operator+(matrice a,matrice b){
matrice c;
int x,y,i;
if(a.r != b.r || a.c != b.c)
exit(0);
c.create(a.r, a.c);
for(x=0;x<c.r;x++)
for(y=0;y<c.c;y++)
c.m[x][y] = a.m[x][y]+b.m[x][y];
return c;
}
| |