0
votes

I initially had a 3x3 matrix that I flattened (so now I have a 1D array that has one row after the other from the initial 3x3 matrix) and I have to multiply it by a 3x1 vector. Any idea of how can I do it? I don't know exactly how to do the iterations. I am doing it with c++.

1
Do you know how to multiply a 3x3 matrix by a 3x1 vector? - Mestkon
To address matrix elements in the "flattened" array, you have to apply something like i = 3 * row + col;. Put it into a helper function with parameters row and col and use it to implement the matrix multiplication as usual. - Scheff's Cat
Are you sure you want to implement that yourself ? Blas/Lapack are very good libraries for matrix implementation. - Caduchon

1 Answers

0
votes

Here is a very simplistic solution using a flattened matrix, and without any bounds checks to keep it simple:

#include <iostream>
#include <vector>

struct matrix2d
{
    std::vector<float> v_;
    size_t x_, y_;
};

std::vector<float> mult3x3(const matrix2d &m, const std::vector<float> &v)
{
    std::vector<float> result;
    for (size_t i=0; i< m.y_; i++)
    {
        float r = 0.0;
        for (size_t j=0; j< m.x_; j++)
        r += m.v_[i*m.x_+j]*v[j];
        result.push_back(r);
    }
    return result;
}

int main()
{
    matrix2d m {.v_ = {1,2,3, 1,2,3, 1,2,3}, .x_=3, .y_=3};
    std::vector<float> v { 1,2,1};

    std::vector<float> result = mult3x3(m, v);
    for (size_t i=0; i< result.size(); i++)
        std::cout << result[i] << ", " << std::endl;
    return 0;
}

See it here