
#include <stdio.h>
#include "matrix.h"


/* Reads a matrix and returns it */
Matrix read_matrix()
{
	Matrix T;
	int n_rows;
	int n_cols;

	printf("Input the size of the matrix (numbers of rows followed by number of columns): ");
	scanf("%d %d", &n_rows, &n_cols);

	T = allocate_matrix(n_rows, n_cols); // allocate space for the elements of the matrix

	printf("Input the %d x %d matrix:\n", T.rows, T.cols);
	for (int i = 0; i < T.rows; i++)
		for (int j = 0; j < T.cols; j++)
			scanf("%f", &T.elements[i][j]); // read element (i, j)

	return T; // return the read matrix
}

/* Outputs matrix A */
void output_matrix(char *statement, Matrix A)
{
	printf(statement);
	for (int i = 0; i < A.rows; i++) { // output i-th row
		for (int j = 0; j < A.cols; j++)
			// output j-th element of i-th row
			printf("%5.2f ", A.elements[i][j]);
		printf("\n");
	}
}


/* Allocates space for a vector, and sets its size */
Vector allocate_vector(int dim)
{
	Vector V;

	V.dim = dim;

	// Create an array of <dim> floats and make V.elements point to it
	V.elements = (float *) malloc( sizeof(float) * dim );

	return V;
}


/* Allocates space for a matrix, and sets its size */
Matrix allocate_matrix(int n_rows, int n_cols)
{
	Matrix T;

	T.rows = n_rows;
	T.cols = n_cols;

	// Create an array of n_rows pointers and make T.elements point to it
	T.elements = (float **) malloc( sizeof(float *) * n_rows );

	for (int i = 0; i < n_rows; i++) {
		// Create an array of n_cols floats and make T.elements[i] point to it
		T.elements[i] = (float *) malloc( sizeof(float) * n_cols );
	}

	return T;
}

void free_matrix(Matrix A)
{
	for (int i = 0; i < A.rows; i++)
		free(A.elements[i]);

	free(A.elements);
}
