Go Down

Topic: dynamic arrays, structs and typedefs? (Read 1 time) previous topic - next topic

aeemnrsu

Mar 23, 2012, 03:34 am Last Edit: Mar 23, 2012, 04:41 am by aeemnrsu Reason: 1
I am trying to implement a Kalman filter on the Arduino and I've had a slew of problems with dealing with matrices and the math between them. At first I thought just using two dimensional arrays would be fine (my two main languages being python and MATLAB, how could anything go wrong), but I ended up writing a new set of functions for each size which was head ache inducing when I found errors in my copy pasted code. As I was about to write a Matrix library using classes in C++, I was told about dynamic arrays.  These seem complicated, but it seems to be exactly what I need as it allows me to return a Matrix, as well as have a decent run time. I realized quickly I needed the size of my matrix to do matrix manipulations so I attempted to use a struct to hold all of the matrix's data. Unfortunately I have not implemented a struct before as well.  My code doesn't compile as of now, but I've included it anyways. It seems it's too big...so pastebin?
Matrix.c http://pastebin.com/ZaFW15MF
Matrix.h http://pastebin.com/hrp6VGuy

First question:
I read somewhere that typedef was actually what I needed to use to return struct like objects in c. Is this what I need?
Code: [Select]

typedef struct matrix_struct {
   float **value; // 2 dimensional dynamic array of value in the matrix
   int numRow;    // number of rows of Matrix
   int numCol;    // number of columns of Matrix
 }  Matrix;

as opposed to what I have:
Code: [Select]

struct Matrix {
   float **value; // 2 dimensional dynamic array of value in the matrix
   int numRow;    // number of rows of Matrix
   int numCol;    // number of columns of Matrix
 }  ;


Second question:
say I called d=addMatrix(multMatrix(a,b),c)
multMatrix(a,b) creates a new matrix. Do I have to deallocate this matrix data?
similarly if I already had an allocated Matrix a, and then I assigned the solution to one of my functions to a.
like this:
Code: [Select]

Matrix a=eye(3,3);
a=addMatrix(a,b);


Third question:
Is there any sort of simple error handling? I tend to mix up rows and columns a lot and I rather not have my code break.
Should I just have it print out some kind of error message via the Serial communication?

Nick Gammon

This gives a pointer to a pointer to a float:

Code: [Select]
    float **value; // 2 dimensional dynamic array of value in the matrix

Don't you just want a pointer to a float? (of course, there will be more than one of them).

I hope these arrays aren't going to get too big, you don't have a lot of memory.

You could consider using the Standard Template Library. That lets you have dynamic arrays.
http://www.gammon.com.au/electronics

aeemnrsu

The biggest one is a 9x9 matrix.

As for pointers...I'm still new to C coding
I think I need a pointer to an array of pointers to an array of floats?

Go Up