matrix.c 1.82 KB
#include "matrix.h"
#include <stdio.h>
#include <stdlib.h>





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 ) {
			for (int j = 0; j < i; j++){
				free(ret->data[j]);
			}
			free(ret->data);
			free(ret);
			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_null (matrix* m){
	
	int rows = matrix_get_rows(m);
	int columns = matrix_get_columns(m);
	
	for (int i = 0; i < rows; i++){
		for (int j = 0; j < columns; j++){
			set (m, i, j, 0);
		}
	}
	
}

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;
	int rows = matrix_get_rows(m1);
	int columns = matrix_get_columns(m1);
	int m2_columns = matrix_get_columns(m2);
	int m2_rows = matrix_get_rows(m2);

	//Matrix dimension check
	if (rows != m2_rows ||  columns != m2_columns ){
		return 0;
	} 
	
	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;

}