Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I multiply a matrix by a vector in MathNet Library?

Tags:

c#

I am working on a project that needs using linear algebra method in it. I decided to use MathNet Numerics library and I want to multiply a matrix by a vector. I couldn't find a function in MathNet that can do this. How can I multiply a matrix by a vector?

like image 216
janbazi Avatar asked Jan 30 '26 22:01

janbazi


1 Answers

A kind of this:

Matrix<double> M = Matrix<double>.Build.DenseOfArray(new double[,]
{
    { 1, 2 },
    { 3, 6 }
});

Vector<double> V = Vector<double>.Build.DenseOfArray(new double[] { 3, 4 });

Vector<double> MV = M * V;
Vector<double> VM = V * M;

Console.WriteLine($"M {M}");
Console.WriteLine($"V {V}");
Console.WriteLine($"M*V {MV}");
Console.WriteLine($"V*M {VM}");

It gives:

M DenseMatrix 2x2-Double
1  2
3  6

V DenseVector 2-Double
3
4

M*V DenseVector 2-Double
11
33

V*M DenseVector 2-Double
15
30

But make sure they are of the same height or you'll get

System.ArgumentException: Matrix dimensions must agree...

like image 83
Alex Avatar answered Feb 01 '26 11:02

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!