Jim

Matrix plus

#include <stdio.h>
#include <stdlib.h>
struct matrix {
int rows;
int columns;
double **data;
};
typedef struct matrix matrix;
matrix* matrix_init(int rows, int columns){
matrix* ret;
if ( (ret = (matrix*) malloc (sizeof(matrix))) == NULL){
return 0;
}
ret->rows = rows;
ret->columns = columns;
if ( (ret->data = (double **) malloc(rows * sizeof(double *))) == NULL ) {
free(ret);
return 0;
}
for (int i = 0; i < rows; i++){
if ( ( ret->data[i] = (double *)malloc (columns * sizeof(double))) == NULL ) {
return 0;
}
}
return ret;
}
void matrix_free(matrix* m)
{
for (int i = 0; i < m->rows; i++){
free (m->data[i]);
}
free(m->data);
free(m);
}
void set(matrix* m, int i, int j, double value)
{
m->data[i][j] = value;
}
double get(matrix* m, int i, int j){
return m->data[i][j];
}
int matrix_get_rows (matrix *m){
return m->rows;
}
int matrix_get_columns (matrix *m){
return m->columns;
}
void matrix_print(matrix* m){
for (int i=0; i < m->rows; i++){
for (int j=0; j < m->columns; j++){
printf ("%lf ", m->data[i][j]);
}
printf("\n");
}
}
matrix* matrix_summ (matrix *m1,matrix *m2){
matrix *m3;
//TODO: check matrix dimensions
int rows = matrix_get_rows(m1);
int columns = matrix_get_columns(m1);
m3 = matrix_init(rows, columns);
for (int i = 0; i < rows; i++){
for (int j=0; j < columns; j++){
double res = get(m1, i, j);
res += get(m2, i,j);
set(m3, i, j, res);
}
}
return m3;
}
int main(){
matrix *m1,*m2, *m3;
m1 = matrix_init (3,3);
m2 = matrix_init (3,3);
for(int i=0; i < matrix_get_rows(m1); i++){
for (int j=0; j < matrix_get_columns(m1); j++){
set(m1, i, j, 1);
}
}
//TODO: null before set
int n = matrix_get_rows(m2);
if (matrix_get_columns(m2) < n )
n = matrix_get_columns(m2);
for(int i=0; i < n; i++){
set(m2, i, i, 1);
}
m3 = matrix_summ (m1, m2);
matrix_print (m1);
matrix_print (m2);
matrix_print (m3);
matrix_free (m1);
matrix_free (m2);
matrix_free (m3);
return 0;
}
... ...