Algorithms_in_C 1.0.0
Set of algorithms implemented in C.
Loading...
Searching...
No Matches
qr_decomposition.c File Reference

Program to compute the QR decomposition of a given matrix. More...

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "qr_decompose.h"
Include dependency graph for qr_decomposition.c:

Functions

int main (void)
 main function
 

Detailed Description

Program to compute the QR decomposition of a given matrix.

Author
Krishna Vedala

Function Documentation

◆ main()

int main ( void  )

main function

19{
20 double **A;
21 unsigned int ROWS, COLUMNS;
22
23 printf("Enter the number of rows and columns: ");
24 scanf("%u %u", &ROWS, &COLUMNS);
25 if (ROWS < COLUMNS)
26 {
27 fprintf(stderr,
28 "Number of rows must be greater than or equal to "
29 "number of columns.\n");
30 return -1;
31 }
32
33 printf("Enter matrix elements row-wise:\n");
34
35 A = (double **)malloc(ROWS * sizeof(double *));
36 for (int i = 0; i < ROWS; i++)
37 A[i] = (double *)malloc(COLUMNS * sizeof(double));
38
39 for (int i = 0; i < ROWS; i++)
40 for (int j = 0; j < COLUMNS; j++) scanf("%lf", &A[i][j]);
41
42 print_matrix(A, ROWS, COLUMNS);
43
44 double **R = (double **)malloc(sizeof(double *) * ROWS);
45 double **Q = (double **)malloc(sizeof(double *) * ROWS);
46 if (!Q || !R)
47 {
48 perror("Unable to allocate memory for Q & R!");
49 return -1;
50 }
51 for (int i = 0; i < ROWS; i++)
52 {
53 R[i] = (double *)malloc(sizeof(double) * COLUMNS);
54 Q[i] = (double *)malloc(sizeof(double) * ROWS);
55 if (!Q[i] || !R[i])
56 {
57 perror("Unable to allocate memory for Q & R.");
58 return -1;
59 }
60 }
61
62 clock_t t1 = clock();
63 qr_decompose(A, Q, R, ROWS, COLUMNS);
64 double dtime = (double)(clock() - t1) / CLOCKS_PER_SEC;
65
66 print_matrix(R, ROWS, COLUMNS);
67 print_matrix(Q, ROWS, COLUMNS);
68 printf("Time taken to compute: %.4g sec\n", dtime);
69
70 for (int i = 0; i < ROWS; i++)
71 {
72 free(A[i]);
73 free(R[i]);
74 free(Q[i]);
75 }
76 free(A);
77 free(R);
78 free(Q);
79 return 0;
80}
#define malloc(bytes)
This macro replace the standard malloc function with malloc_dbg.
Definition malloc_dbg.h:18
#define free(ptr)
This macro replace the standard free function with free_dbg.
Definition malloc_dbg.h:26
void qr_decompose(double **A, double **Q, double **R, int M, int N)
Decompose matrix using Gram-Schmidt process.
Definition qr_decompose.h:142
void print_matrix(double **A, int M, int N)
function to display matrix on stdout
Definition qr_decompose.h:22
Here is the call graph for this function: