How can I multiply two matrices in C#?

2020-02-28 07:53发布

问题:

Like described in the title, is there some library in the Microsoft framework which allows to multiply two matrices or do I have to write my own method to do this? // I've got an answer to this by now

Second question: I wrote this multi class with a MultiplyMatrix method but it doesn't work like I want to. Can anyone help and tell where I made a mistake?

class multi
    {
        public void MultiplyMatrix(double[,] _A, double[,] _B, int _n, int _m, int _r)
        {
            int n, m, r;
            double si;
            n = _n;
            m = _m;
            r = _r;
            double[,] A = new double[n, m];
            double[,] B = new double[m, r];
            double[,] C = new double[n, r];
            A = _A;
            B = _B;
            try
            {
                for (int i = 0; i < n; i++)
                {
                    for (int j = 0; j < r; j++)
                    {
                        si = 0;
                        for (int k = 0; k < m; k++)
                        {
                            si += A[i, m + k] + B[k, r + j];
                        }
                        C[i, r + j] = si;
                    }
                }
                for (int i = 0; i < C.Length; i++)
                {
                    for (int j = 0; j < C.Length; j++)
                    {
                        Console.Write(C[i, j]+" ");
                        if (j % 3 == 0)
                            Console.WriteLine();
                    }
                }
            }
            catch (IndexOutOfRangeException) { } // I always get this exception

        }

    }

I forgot to tell: I want to make a webservice to multiply on it.

Thanks:)

回答1:

There is nothing built into .NET. You will have to write the multiplication yourself or use some third party library. I've blogged about one way to achieve this comparing two different implementations : a standard naive algorithm and one using unsafe code.



回答2:

Whilst there's no built in Maths framework to do this in .NET (could use XNA's Maths library), there is a Matrix in the System.Windows.Media namespace. The Matrix structure has a Multiply method which takes in another Matrix and outputs a Matrix.

Matrix matrix1 = new Matrix(5, 10, 15, 20, 25, 30);
Matrix matrix2 = new Matrix(2, 4, 6, 8, 10, 12);

// matrixResult is equal to (70,100,150,220,240,352) 
Matrix matrixResult = Matrix.Multiply(matrix1, matrix2);

// matrixResult2 is also
// equal to (70,100,150,220,240,352) 
Matrix matrixResult2 = matrix1 * matrix2;

This is mainly used for 2D transformation:

Represents a 3x3 affine transformation matrix used for transformations in 2-D space.

but if it suits your needs, then there's no need for any third party libraries.



回答3:

The logic for multiplying the two matrices is shown below in the image:

A row of the first Matrix and Column of the second Matrix are taken. The corresponding terms are multiplied and added together. They are stored in a location(Matrix C) that is specified by the Row Number of Matrix A and Column Number of Matrix B. The simplest way to do this in your code is by adding a total of 3 for loops. The first two loops simulate the Row Number and Column Number. The third for loop adds the three multiplied pair elements together and stores their result in the C Matrix. Watch the code below:

    public void MultiplyMatrix()
    {
        if (a.GetLength(1) == b.GetLength(0))
        {
            c = new int[a.GetLength(0), b.GetLength(1)];
            for (int i = 0; i < c.GetLength(0); i++)
            {
                for (int j = 0; j < c.GetLength(1); j++)
                {
                    c[i, j] = 0;
                    for (int k = 0; k < a.GetLength(1); k++) // OR k<b.GetLength(0)
                        c[i, j] = c[i, j] + a[i, k] * b[k, j];
                }
            }
        }
        else
        {
            Console.WriteLine("\n Number of columns in First Matrix should be equal to Number of rows in Second Matrix.");
            Console.WriteLine("\n Please re-enter correct dimensions.");
            Environment.Exit(-1);
        }
    }

Source http://www.Code-Kings.Blogspot.com



回答4:

multiply 2 matrix :

public double[,] MultiplyMatrix(double[,] A, double[,] B)
    {
        int rA = A.GetLength(0);
        int cA = A.GetLength(1);
        int rB = B.GetLength(0);
        int cB = B.GetLength(1);
        double temp = 0;
        double[,] kHasil = new double[rA, cB];
        if (cA != rB)
        {
            Console.WriteLine("matrik can't be multiplied !!");
        }
        else
        {
            for (int i = 0; i < rA; i++)
            {
                for (int j = 0; j < cB; j++)
                {
                    temp = 0;
                    for (int k = 0; k < cA; k++)
                    {
                        temp += A[i, k] * B[k, j];
                    }
                    kHasil[i, j] = temp;
                }
            }
        return kHasil;
        }
    }


回答5:

Although you can multiply matrices by an iterative approach (for loops), performing the calculations with linear algebra will clean up your code and will give you performance gains that are several times faster!

There is a free library available in nuget - MathNet.Numerics. It makes it extremely easy to multiply matrices:

Matrix<double> a = DenseMatrix.OfArray(new double[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } });
Matrix<double> b = DenseMatrix.OfArray(new double[,] { { 1 }, { 2 }, { 3 } });
Matrix<double> result = a * b;

It has no dependencies and can be used in .net core 2.0, making it an excellent choice to avoid iterative matrix multiplication techniques and take advantage of linear algebra.



回答6:

CSML - C# Matrix Library - is a compact and lightweight package for numerical linear algebra. Many matrix operations known from Matlab, Scilab and Co. are implemented. See this!



回答7:

There are no such built in libraries. Unless you are using XNA - it has a Matrix class, though it is limited and designed for 3D games.

There are many matrix libraries for .NET though.



回答8:

namespace matrix_multiplication
{
    class Program
    {
        static void Main(string[] args)
        {
            int i, j;
            int[,] a = new int[2, 2];
            Console.WriteLine("Enter no for 2*2 matrix");
            for (i = 0; i < 2; i++)
            {
                for (j = 0; j < 2; j++)
                {
                    a[i, j] = int.Parse(Console.ReadLine());
                }
            }
            Console.WriteLine("First matrix is:");
            for (i = 0; i < 2; i++)
            {
                for (j = 0; j < 2; j++)
                {
                  Console.Write(a[i,j]+"\t");
                }
                Console.WriteLine(); 
            }


            int[,] b = new int[2, 2];
            Console.WriteLine("Enter no for 2*2 matrix");
            for (i = 0; i < 2; i++)
            {
                for (j = 0; j < 2; j++)
                {
                    b[i, j] = int.Parse(Console.ReadLine());
                }
            }
            Console.WriteLine("second matrix is:");
            for (i = 0; i < 2; i++)
            {
                for (j = 0; j < 2; j++)
                {
                    Console.Write(b[i, j] + "\t");
                }
                Console.WriteLine();
            }

            Console.WriteLine("Matrix multiplication is:");
            int[,] c = new int[2, 2];
            for (i = 0; i < 2; i++)
            {
                for (j = 0; j < 2; j++)
                {


                    c[i,j]=0;
                     for (int k = 0; k < 2; k++)
                     {
                         c[i, j] +=  a[i, k] * b[k, j];
                     }
                 }
            }
            for (i = 0; i < 2; i++)
            {
                for (j = 0; j < 2; j++)
                {
                    Console.Write(c[i, j]+"\t");
                }
                Console.WriteLine();
            }

            Console.ReadKey();
        }
    }
}

output

Enter no for 2*2 matrix

8
7
6
0

First matrix is:

8       7
6       0

Enter no for 2*2 matrix

4
3
2
1

second matrix is:

4       3
2       1

Matrix multiplication is:

46      31
24      18


回答9:

Below is the method to multiply int[3,4] matrix with int[4,3] matrix, it has time complexity of O(n cube) or Cubic time

class Program { static void Main(string[] args) {

        MultiplyMatrix();
    }

    static void MultiplyMatrix()
    {
        int[,] metrix1 = new int[3,4] { { 1, 2,3,2 }, { 3, 4,5,6 }, { 5, 6,8,4 } };
        int[,] metrix2 = new int[4, 3] { { 2, 5, 3 }, { 4, 5, 1 }, { 8, 7, 9 }, { 3, 7, 2 } };
        int[,] metrixMultplied = new int[3, 3];

        for (int row = 0; row < 3; row++)
        {
            for (int col = 0; col < 3; col++)
            { 
                for(int i=0;i<4;i++)
                {
                    metrixMultplied[row, col] = metrixMultplied[row, col] + metrix1[row, i] * metrix2[i, col];

                }
                Console.Write(metrixMultplied[row, col] + ", ");                   
            }
            Console.WriteLine();
        }
        Console.ReadLine();
    }
}


回答10:

I wrote a small program to multiply two 3 x 3 matrices, as part of my neural network for my A-level project. Hope people find it useful.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _3_x_3_Matrix_multiplier
{
    class Program
    {
        static void Main(string[] args)
        {
            int[,,] matrix = new int[3, 3, 3];
            for (int z = 0; z < 2; z++)
            {
                for (int y = 0; y < 3; y++)
                {
                    for (int x = 0; x < 3; x++)
                    {
                        Console.WriteLine("element: {0} , {1}", x, y);
                        matrix[x, y, z] = int.Parse(Console.ReadLine());
                    }
                }
            }
            for (int xm = 0; xm < 3; xm++)
            {
                for (int ym = 0; ym < 3; ym++)
                {
                    for (int zm = 0; zm < 3; zm++)
                    {
                        matrix[xm, ym, 2] += (matrix[0 + zm, ym, 0] * matrix[xm, 0 + zm, 1]);
                    }
                }
            }
            for (int i = 0; i < 3; i++)
            {
                Console.Write("\n");
                for (int j = 0; j < 3; j++)
                {
                    Console.Write(matrix[j, i, 2] + " ");
                }
            }
            Console.ReadLine();
        }
    }
}


回答11:

Here is my code : 4*4 matrix

for (int i = 0; i < 4; i++)
{        
    int column = 0;
    while (column < 4)
    {
        int count = 0;
        for (int j = 0; j < 4; j++)
        {
            matrixResult[i, column] += Convert.ToInt32(matrixR[i, j] * matrixT[count, column]);
            count = count + 1;
        }
        column = column + 1;
    }       

}



标签: c# math