Paul Warnick
Paul Warnick

Reputation: 933

How should I multiply two matrices in C++?

Note: I'm using the standard library for C++, and am storing matrices as multidimensional vectors (see example below).

I'm having trouble finding the proper function to multiply two matrices in C++. To clarify what I'm trying to do:

A = | a1 a2 |  B = | b1 |
    | a3 a4 |      | b2 |

Result = | (a1 * b1 + a2 * b2) |
         | (a3 * b1 + a4 * b2) |

Obviously I could do this using a simple algorithm but I'm trying to find if there's a function to do this.

My specific example in C++:

#include <vector>

std::vector<std::vector<double>> A;
A.push_back({ 0.96, 0.56 });
A.push_back({ 0.01, 0.41 });

std::vector<std::vector<double>> B;
B.push_back({ 1.331749 });
B.push_back({ 1.0440705 });

Result = (A * B);

Where "Result" would be:

| 1.8631586 |
| 0.4413864 |

How should I go about doing the above?

Upvotes: 0

Views: 172

Answers (2)

Brandon Busby
Brandon Busby

Reputation: 21

I do not believe there is a function to multiply vectors together like matrices, however it would not be that difficult to implement on your own. I would suggest creating a matrix class. With this you could overload the * operator. This would look like the following:

class Matrix
{
private:
    // Whatever implementation you choose.
    // This would probably be done with a vector of vectors.
public:
    Matrix& operator*(const Matrix&) const;
    // Public interface
}

This would allow you to develop a simple algorithm for multiplying two matrices.

Upvotes: 1

Sam Varshavchik
Sam Varshavchik

Reputation: 118340

No, there are no functions in the C++ library for vector multiplication. There are some building blocks, like std::for_each, std::copy, and std::transform, that can be used to implement them, but it's up to you implement the complete algorithm by yourself.

There might be some libraries floating around, somewhere on the Intertubes, that implement these algorithms. You can try your luck with Google.

Upvotes: 1

Related Questions