-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlr_norm_eq.c
98 lines (78 loc) · 2.33 KB
/
lr_norm_eq.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <stdio.h>
#include <stdlib.h>
#include "utils.h"
// Function to invert 2x2 matrix
double invertMatrix(double **matrix, double **result)
{
// Check if matrix is not singular
double determinant = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
if (determinant == 0)
return 0; // Singular matrix
// Invert matrix
result[0][0] = matrix[1][1] / determinant;
result[0][1] = -matrix[0][1] / determinant;
result[1][0] = -matrix[1][0] / determinant;
result[1][1] = matrix[0][0] / determinant;
return 1; // Inversion successful
}
double *calculateTheta(double **X, int rows, int cols, double *y)
{
// Create temp matrices
double **T1 = allocateMatrix(cols, cols);
double **IM = allocateMatrix(cols, cols);
double **T2 = allocateMatrix(cols, rows);
// Create temp vector
double *theta = (double *)malloc(sizeof(double) * cols);
// Transpose matrix
double **X_T = transposeMatrix(X, rows, cols);
// Multiply and inverse matrix
matrixMultiply(X_T, cols, rows, X, rows, cols, T1);
invertMatrix(T1, IM);
printf("Matrix IM with %d rows and %d cols.\n", cols, cols);
printMatrix(IM, cols, cols, 4);
// Multiply inverse matrix on X_T and y
matrixMultiply(IM, cols, cols, X_T, cols, rows, T2);
matrixVectorMultiply(T2, cols, rows, y, rows, theta);
// Free memory
freeMatrix(T1, cols);
freeMatrix(IM, cols);
freeMatrix(T2, cols);
freeMatrix(X_T, cols);
return theta;
};
int main()
{
// Declaration of rows and cols in A matrix
int rows = 3, cols = 2;
// Init X
double **X = allocateMatrix(rows, cols);
// Fill X
X[0][0] = 1;
X[0][1] = 1;
X[1][0] = 1;
X[1][1] = 2;
X[2][0] = 1;
X[2][1] = 3;
// Print X
printf("Matrix X with %d rows and %d cols.\n", rows, cols);
printMatrix(X, rows, cols, 0);
// Init y and result
double *y = (double *)malloc(sizeof(double) * rows);
double *theta;
// Fill y
y[0] = 1;
y[1] = 2;
y[2] = 3;
// Print y
printf("Vector y with size %d.\n", rows);
printVector(y, rows, 0);
// Calculate theta
theta = calculateTheta(X, rows, cols, y);
printf("Vector theta with size %d.\n", cols);
printVector(theta, cols, 4);
// Free memory
freeMatrix(X, rows);
free(y);
free(theta);
return 0;
}