manbearpig
manbearpig

Reputation: 1

C# Trying to swap one element in a list but ending up swapping them all

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|

Upvotes: 0

Views: 67

Answers (2)

greg b
greg b

Reputation: 13

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());
 }

Upvotes: 0

Blindy
Blindy

Reputation: 67380

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.

Upvotes: 1

Related Questions