About Me

My photo
I'm an undergraduate of Sri Lanka Institute of Information Technology(SLIIT).

Matrix with List<>

Hello everyone!!!

Have you ever deal with matrix in you coding? If yes, how did you represent a matrix? Most probably you answer will 2D array. 2 D array is the most common matrix representation that all most all the coders using. But I have tried out different way and its successes. I used list to represent matrix. I believe we can easily have matrices graphical representation using this method.


 
You can consider single element as an integer variable.
By adding this kind of set of integer variable you can create an integer list. It is a matrix row.
By adding set of rows you can create a matrix.
I used this method to add a matrix addition question with two matrix with one answer and three wrong answers.

public class Row
{
    public List<int> cell = new List<int>();

    public void addCell(int element)
    {
            cell.Add(element);//add a single element
    }
}
public class Matrices
{
     public List<Row> matrix = new List<Row>();

     //add a row
     public void addMatrix(Row matrixRow)
     {
         matrix.Add(matrixRow);
     }

 }

Add following matrix in to lists using above classes

int A[,]=new int[4,2];
            A[,]={{1,2,3,4},{5,6,7,8}};
            int row=2;
            int col=4;
            Matrices mA = new Matrices ();

            //adding values for matrix
            for (int i = 0; i < row; i++)
            {
                Row rowA = new Row();

                for (int j = 0; j < col; j++)
                {
                    rowA.addCell(A[i, j]);
                }

                mA.addMatrix(rowA);
            }

Retrieve matrix elements

      List<int> elemntList= new List<int>();
            foreach (Row r1 in rowA)
            {

                  elemntList = r1.cell;

                  foreach (int element in elemntList)
                  {
                                Console.Write(element);
                  }
                                                               
                 Console.WriteLine();
                           
             }

Hope this post will help to you.
Don’t forget to leave a comment. Your suggestions are highly welcome.
Cheers!!!



0 comments:

Post a Comment