TheAlgorithms-C/numerical_methods/qr_decomposition.c

81 lines
1.9 KiB
C
Raw Normal View History

/**
* @file
2020-06-05 19:20:37 +03:00
* \brief Program to compute the [QR
* decomposition](https://en.wikipedia.org/wiki/QR_decomposition) of a given
* matrix.
2020-06-06 21:51:49 +03:00
* \author [Krishna Vedala](https://github.com/kvedala)
*/
2020-04-20 19:07:19 +03:00
#include <math.h>
#include <stdio.h>
2020-04-20 19:07:19 +03:00
#include <stdlib.h>
2020-05-29 19:34:58 +03:00
#include <time.h>
#include "qr_decompose.h"
2020-04-20 19:07:19 +03:00
/**
* main function
*/
2020-04-20 19:07:19 +03:00
int main(void)
{
double **A;
unsigned int ROWS, COLUMNS;
printf("Enter the number of rows and columns: ");
scanf("%u %u", &ROWS, &COLUMNS);
if (ROWS < COLUMNS)
{
fprintf(stderr,
"Number of rows must be greater than or equal to "
"number of columns.\n");
return -1;
}
printf("Enter matrix elements row-wise:\n");
A = (double **)malloc(ROWS * sizeof(double *));
for (int i = 0; i < ROWS; i++)
A[i] = (double *)malloc(COLUMNS * sizeof(double));
for (int i = 0; i < ROWS; i++)
for (int j = 0; j < COLUMNS; j++) scanf("%lf", &A[i][j]);
2020-04-20 19:07:19 +03:00
print_matrix(A, ROWS, COLUMNS);
double **R = (double **)malloc(sizeof(double *) * ROWS);
double **Q = (double **)malloc(sizeof(double *) * ROWS);
2020-04-20 19:07:19 +03:00
if (!Q || !R)
{
perror("Unable to allocate memory for Q & R!");
return -1;
}
for (int i = 0; i < ROWS; i++)
{
R[i] = (double *)malloc(sizeof(double) * COLUMNS);
Q[i] = (double *)malloc(sizeof(double) * ROWS);
2020-04-20 19:07:19 +03:00
if (!Q[i] || !R[i])
{
perror("Unable to allocate memory for Q & R.");
return -1;
}
}
2020-05-29 19:34:58 +03:00
clock_t t1 = clock();
2020-04-20 19:07:19 +03:00
qr_decompose(A, Q, R, ROWS, COLUMNS);
2020-05-29 19:34:58 +03:00
double dtime = (double)(clock() - t1) / CLOCKS_PER_SEC;
2020-04-20 19:07:19 +03:00
print_matrix(R, ROWS, COLUMNS);
print_matrix(Q, ROWS, COLUMNS);
2020-04-20 19:07:19 +03:00
printf("Time taken to compute: %.4g sec\n", dtime);
for (int i = 0; i < ROWS; i++)
{
free(A[i]);
2020-04-20 19:07:19 +03:00
free(R[i]);
free(Q[i]);
}
free(A);
2020-04-20 19:07:19 +03:00
free(R);
free(Q);
return 0;
2020-06-06 21:51:49 +03:00
}