How to make a sum of two matrices generating a third in c#?

Asked

Viewed 2,339 times

2

I can’t do it, I tried using the FOR loop and also the IF to store in the matrix before making the sum, but my knowledge in c# is scarce. and the matrix is a 2x2.

  • What have you tried? Add your attempt to the question.

  • 1

    Enjoy and do also the Tour of the site to get to know how it works. And also how to ask

1 answer

2

The result of a sum of an order matrix 2 x 2 is the sum of the corresponding elements of their positions, example:

inserir a descrição da imagem aqui

Source: http://mundoeducacao.bol.uol.com.br/matematica/adicao-subtracao-matrizes.htm

To encode this in , is very simple, the declaration of a 2 x 2 integer matrix would be:

int[,] matrizA = new int[2, 2];

allocation in each position:

matrizA[0, 0] = 1;
matrizA[0, 1] = 2;
matrizA[1, 0] = 3;
matrizA[1, 1] = 4;

and recovery:

int i0 = matrizA[0, 0];
int i1 = matrizA[0, 1];
int i2 = matrizA[1, 0];
int i3 = matrizA[1, 1];

A minimal example:

static void Main(string[] args)
{
    int[,] matrizA = new int[2, 2];
    int[,] matrizB = new int[2, 2];

    matrizA[0, 0] = 1;
    matrizA[0, 1] = 2;
    matrizA[1, 0] = 3;
    matrizA[1, 1] = 4;

    matrizB[0, 0] = 1;
    matrizB[0, 1] = 2;
    matrizB[1, 0] = 3;
    matrizB[1, 1] = 4;

    int[,] matrizC = Sum(matrizA, matrizB);
    View(matrizC);

    System.Console.ReadKey();

}

public static int[,] Sum(int[,] a, int[,] b)
{
    int[,] result = new int[a.Rank, a.Rank];
    for (int i = 0; i < a.Rank; i++)
        for (int j = 0; j < a.Rank; j++)
            result[i, j] = a[i, j] + b[i, j];
    return result;
}

public static void View(int[,] a)
{
    for (int i = 0; i < a.Rank; i++)
    {
        for (int j = 0; j < a.Rank; j++)
            System.Console.Write("{0} ", a[i, j]);
        System.Console.WriteLine();
    }

}

that example running online where the expected result would be:

2 4 
6 8 

in that code the method static sum is responsible for summing the corresponding elements where the first for is the control of lines and the second for the of columns, so long as it’s over lines and columns of the available matrix and this method to be executed in larger matrix only of the same amount of elements, example: 3 x 3, 4 x 4, etc.., and the method static view will display the existing elements in a matrix.

References:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.