## Matrices (Part 2)

Previous post on same subject

At first, what we need before doing any maths is to create tables. Again, tables are nothing else than continuous memory spaces that we need to reserve in the heap memory. Here are four different ways of table initialization.

The simplest [ ], the roughest[ ], the wierdest[ ] *:

```	const uint8_t size = 9; // Set size
double mA[size] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; // set variable
free(mA); // Free memory space after use in order to avoid memory leakage
```

* Check the appropriate box according to your taste ðŸ˜‰
Note that in spite of the lack of * sign before mA, mA is (implicitly) a pointer.

Let’s use a smarter and more dynamic way of creating tables using the malloc function from the stdlib.h library (There are tons of reference on Google).

```	uint8_t size = 9;
double* mA = (double*)malloc(size * sizeof(double));
free(mA);
```

That’s better, and we could now think about encapsulating this code in a function. Here is the first option:

```double* PlainMAT::Initialize(uint8_t size) {
double* mA = (double*)malloc(size * sizeof(double));
return(mA);
}
```

And the way to use it in a sketch, after creating a ‘MAT‘ object out of the ‘PlainMAT‘ library:

```	uint8_t size = 9;
double* mA = MAT.Initialize(size);
free(mA);
```

And this is an other option:

```void PlainMAT::Initialize(double** mA, uint8_t size) {
*mA = (double*)malloc(size * sizeof(double));
}
```

and again the way to use it in a sketch:

```	uint8_t size = 9;
double* mA;
MAT.Initialize(&mA, size);
free(mA);
```

### One Comment

1. […] Next post on same subject Tags: Matrices, Programming Comment (RSS)  |  Trackback […]