0

I've made a Matrix object, which looks like the following:

using System;
using System.Collections.Generic;

public class Matrix
{
  public List<List<float>> rows = new List<List<float>>();

  public Matrix()
  {

  }

  public Matrix(List<List<float>> Rows)
  {
    rows = Rows;
  }

And trying to define a function, matrix-multiplication. However, when I try to access the element (i,j) in a matrix, and swap it, it swaps every element in that column?

public static Matrix operator*(Matrix A, Matrix B)
    {
      List<List<float>> input = new List<List<float>>();
      List<float> input_list = new List<float>();

      for(int i = 0; i < B.rows.Count; i++)
      {
        input_list.Add(0);
      }

      for(int i = 0; i < A.rows.Count; i++)
      {
        input.Add(input_list);
      }

      Matrix C = new Matrix(input);

      Console.WriteLine(C);
      // output
      // |0 0 0|
      // |0 0 0|
      // |0 0 0|
      C.rows[0][0] = 69;
      // output
      // |69 0 0|
      // |69 0 0|
      // |69 0 0| ???          
      Console.WriteLine(C);
      return C;

I expect C.rows[0][0] = 69; to result in the output |69 0 0| |0 0 0| |0 0 0|

  • 2
    A `List` is a [reference type](https://stackoverflow.com/q/5057267/11683). `input.Add(input_list);` adds the same instance `input_list` multiple times. Apparently you wanted `input.Add(new List());`, but a list of lists is not really a good way to [represent a matrix](https://stackoverflow.com/q/13035464/11683) in the first place. – GSerg Jun 02 '21 at 16:57

2 Answers2

1

Replace input.Add(input_list); with input.Add(input_list.ToList());, since you want different list instances.

This is an absolutely dreadful way of building a matrix though. You're taking one of the most optimized data structures in all of computer science and trying to cobble it together out of play dough and hope. Especially bad since .Net has a built-in matrix class which is heavily optimized and vectorized.

Blindy
  • 65,249
  • 10
  • 91
  • 131
0

This is because you are adding the object reference. using System.Linq;

 for(int i = 0; i < A.rows.Count; i++)
 {
    input.Add(input_list.Select(item => (T)item.Clone()).ToList());
 }
greg b
  • 13
  • 4