[英]How can I multiply two matrices in C#?
如標題中所述,Microsoft 框架中是否有一些庫允許將兩個矩陣相乘,還是我必須編寫自己的方法才能做到這一點? // 我現在已經有了答案
第二個問題:我用 MultiplyMatrix 方法寫了這個多 class 但它不像我想要的那樣工作。 誰能幫忙告訴我哪里出錯了?
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
}
}
我忘了告訴你:我想做一個網絡服務來增加它。
謝謝:)
雖然在 .NET(可以使用 XNA 的數學庫)中沒有內置的數學框架來執行此操作,但System.Windows.Media命名空間中有一個Matrix
。 Matrix 結構有一個Multiply 方法,它接受另一個 Matrix 並輸出一個 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;
這主要用於二維變換:
表示用於二維空間中的變換的 3x3 仿射變換矩陣。
但如果它適合您的需求,那么就不需要任何第三方庫。
乘以 2 矩陣:
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;
}
}
將兩個矩陣相乘的邏輯如下圖所示:
取第一個矩陣的一行和第二個矩陣的列。 相應的項相乘並相加。 它們存儲在由矩陣 A 的行號和矩陣 B 的列號指定的位置(矩陣 C)中。在代碼中執行此操作的最簡單方法是總共添加 3 個 for 循環。 前兩個循環模擬行號和列號。 第三個 for 循環將三個相乘的對元素相加,並將它們的結果存儲在 C 矩陣中。 觀看下面的代碼:
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);
}
}
盡管您可以通過迭代方法(for 循環)將矩陣相乘,但使用線性代數執行計算將清理您的代碼,並使您的性能提升數倍!
nuget - MathNet.Numerics中有一個免費庫。 它使矩陣相乘變得非常容易:
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;
.它沒有依賴關系,可用於 .net 內核 2.0,使其成為的絕佳選擇。
.NET 沒有內置任何內容。 您將不得不自己編寫乘法或使用一些第三方庫。 我已經在博客中介紹了一種比較兩種不同實現的方法:一種標准的朴素算法和一種使用不安全代碼的方法。
CSML - C# 矩陣庫 - 是用於數值線性代數的緊湊輕量級 package。 實現了從 Matlab、Scilab 和 Co. 已知的許多矩陣運算。 看到這個!
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
為 2*2 矩陣輸入 no
8
7
6
0
第一個矩陣是:
8 7
6 0
為 2*2 矩陣輸入 no
4
3
2
1
第二個矩陣是:
4 3
2 1
矩陣乘法是:
46 31
24 18
至少今天,或者更確切地說,從.NET Framework 3.0
開始,我猜Matrix.Multiply會做得最好。
以下是將 int[3,4] 矩陣與 int[4,3] 矩陣相乘的方法,它的時間復雜度為 O(n cube) 或 Cubic time
class 程序 { static 無效 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();
}
}
我編寫了一個小程序來將兩個 3 x 3 矩陣相乘,作為我的 A 級項目的神經網絡的一部分。 希望人們覺得它有用。
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();
}
}
}
這是我的代碼:4*4 矩陣
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;
}
}
如果您有一個助手要生成、迭代和填充一個int[,]
矩陣,如下所示:
public class VisitMatrix{
public static int[,] execute(int rows, int columns, Func<int, int, int> fn)
{
int[,] result = new int[rows, columns];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
result[i, j] = fn(i, j);
}
}
return result;
}
}
現在矩陣乘法就像做一樣微不足道(假設m1.GetLength(1) == m2.GetLength(0)
):
public class MultiplyMatrices{
public static int[,] execute(int[,] m1, int[,] m2, int modulus = 10)
{
return VisitMatrix.execute(m1.GetLength(0), m2.GetLength(1), (i, j) =>
Enumerable.Range(0, m1.GetLength(1)-1)
.Select(k => m1[i, k] * m2[k, j])
.Aggregate(0, (a, b) => a + b, e => e % modulus)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.