Assignment "=" Operator with Matrices


#1

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.

Thanks.


#2

This is the default behavior in C#.

But you can use something like this:

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

or

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

#3

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


#4

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;
            Console.WriteLine(some.Some.ToString());
            some.Some = 100;
            Console.WriteLine(some2.Some.ToString());
        }
}

We got

10
100

https://dotnetfiddle.net/lb7SW5

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)


#5

Excellent. Thanks much for the insight.


(Christoph Rüegg) #6

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.