This repository has been archived by the owner on Jan 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
matrix.c
94 lines (82 loc) · 1.97 KB
/
matrix.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
#include "matrix.h"
struct matrix *
matrix_from_vector(int *vector, size_t order)
{
struct matrix *matrix = malloc(sizeof *matrix);
matrix->order = order;
matrix->data = malloc(order * order * sizeof *(matrix->data));
for (size_t i = 0; i < order*order; i++) {
matrix->data[i] = vector[i];
}
return matrix;
}
struct matrix *
matrix_new(size_t order)
{
struct matrix *matrix = malloc(sizeof *matrix);
matrix->order = order;
matrix->data = malloc(order * order * sizeof *(matrix->data));
return matrix;
}
struct matrix *
matrix_random(size_t order, int lower, int upper, double connectivity)
{
int val;
struct matrix *M = matrix_new(order);
for(size_t i = 0; i < order; i++) {
for(size_t j = 0; j < order; j++) {
if (i == j) {
matrix_set(M, i, j, 0);
continue;
}
if ( (((double)rand())/RAND_MAX) < connectivity )
val = (rand() % (upper - lower + 1)) + lower;
else
val = 0;
matrix_set(M, i, j, val);
}
}
// Set direct conection from first tto last very expensive
//matrix_set(M, 0, order-1, (order/2)*upper);
return M;
}
void
matrix_free(struct matrix *matrix)
{
if(matrix != NULL) {
if(matrix->data != NULL) {
free(matrix->data);
free(matrix);
}
}
}
void
matrix_print(struct matrix *matrix)
{
printf("\t");
for(size_t i =0; i < matrix->order; i++)
printf("%6d\t", i);
printf("\n");
for(size_t i = 0; i < matrix->order; i++) {
printf("%6d\t", i);
for(size_t j = 0; j < matrix->order; j++) {
printf("%6d\t", matrix->data[i * (matrix->order) + j]);
}
printf("\n");
}
}
int
matrix_get(struct matrix *matrix, size_t i, size_t j)
{
return matrix->data[i * (matrix->order) + j];
}
void
matrix_set(struct matrix * matrix, size_t i, size_t j, int e)
{
matrix->data[i * (matrix->order) + j] = e;
}
int *
matrix_getp(struct matrix *matrix, size_t i, size_t j)
{
return &(matrix->data[i * (matrix->order) + j]);
}