tomstewart89 / BasicLinearAlgebra

A library for using matrices and linear algebra on Arduino
MIT License
185 stars 38 forks source link

Custom matrix diagonal values #48

Closed SimonSvis closed 2 years ago

SimonSvis commented 2 years ago

Hi Scott, I'm loving this library. I was wondering would it be possible to somehow make a storage efficient matrix with values in multiple diagonals? The particular matrix would be like the one in the image. image Obviously adding all those zero's would be a waste, thanks in advance for your response!

tomstewart89 commented 2 years ago

Hi @SimonSvis, I'm glad you like the library!

You can probably make a custom matrix type to represent that matrix like so:

struct MultiDiagonal
{
    typedef float elem_t;

    const float delta_t_;
    const float half_delta_t_squared_;

    MultiDiagonal(float delta_t) : delta_t_(delta_t), half_delta_t_squared_(delta_t * delta_t / 2.0) {}

    float operator()(int row, int col) const
    {
        if (row == col)
        {
            return 1.0f;
        }
        else if (row == col - 2)
        {
            return delta_t_;
        }
        else if (row == col - 5)
        {
            return half_delta_t_squared_;
        }
        else
        {
            return 0.0f;
        }
    }
};

Then you can declare that matrix (and specify a delta T) like so:

MultiDiagonal mem(0.01);
BLA::Matrix<8, 8, MultiDiagonal> diag(mem);

From there you should be able to do pretty much anything with diag that you would any other BLA::Matrix.

The only thing to be careful of is that the library currently doesn't make any special accomodations for sparse matrices like this when doing arithmetic. So operations like mutliplication etc will have the same computation cost as for a dense matrix.

Hope that helps!