Assignment "=" Operator with Matrices

It appears that the assignment operator with MathNet linear algebra is functionally different from the standard C# assignment operator. It seems with MathNet, if you say ‘matrix1 = matrix2’, it assigns the same reference/address to both matrices, rather than simply copying the contents of one to the other at a different reference/address/location. Hence the inclusion of a ‘.CopyTo’ method.

Anyone know the reasoning for that? Just curious.


This is the default behavior in C#.

But you can use something like this:

Matrix<double> matrix1 = Matrix<double>.Build.DenseOfMatrix(matrix2);


Matrix<double> matrix1 = matrix2.Map(x => x);

Thanks. I understand that it is the default behavior, but I’m wondering why. If you use an assignment in C# (independent of MathNet), that’s not the default behavior correct? The assignment doesn’t doesn’t refer both to the same memory location. But apparently it does in MathNet. I’m wondering why the difference? Thanks

No, let’s consider the example:

using System;

public class SomeTest
  public int Some { get; set; }

public class Program
        public static void Main(string[] args)
            SomeTest some = new SomeTest { Some = 1 };
            SomeTest some2 = some;
            some2.Some = 10;
            some.Some = 100;

We got


We get the same result since Matrix is a class, not a structure .This is the difference between a value types and a reference types.

You can see good explanation this:

another article:

C# Concepts: Value vs Reference Types (Joseph Albahari)

Excellent. Thanks much for the insight.

Thanks for the explanation! There are a lot of reasons why Math.NET matrices are reference types, including the technical reason that the underlying arrays are always reference types in .Net. It is also what a .Net developer would expect.

This is very different from e.g. MATLAB, and indeed something that needs to be considered when porting code between the two (in addition to the zero-based indexing).

NB: If you need a copy of a vector or matrix, you can also use the Clone method.