using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 矩阵运算
{
class Program
{
static void Main(string[] args)
{
double[][] a =
{
new double[]{1.0,2.0,3.0},
new double[]{4.0,5.0,6.0},
new double[]{7.0,8.0,9.0}
};
double[][] b =
{
new double[]{2.0,-2.0,1.0},
new double[]{1.0,3.0,9.0},
new double[]{17.0,-3.0,7.0}
};
double[][] c =
{
new double[3],
new double[3],
new double[3]
};
Console.WriteLine("相乘结果:");
MatrixMul(a, b, c);
MatrixLog(c);
Console.WriteLine("相加结果:");
MatrixPlus(a, b, c);
MatrixLog(c);
Console.WriteLine("相减结果:");
MatrixSub(a, b, c);
MatrixLog(c);
Console.ReadLine();
}
//矩阵相加
public static void MatrixPlus(double[][] a, double[][] b, double[][] c)
{
if (a == null || b == null || (a.Length != b.Length) || (a[0].Length != b[0].Length))
return;
for (int i = 0; i < a.Length; i++)
{
for (int k = 0; k < a[0].Length; k++)
{
c[i][k] = a[i][k] + b[i][k];
}
}
}
//矩阵相减
public static void MatrixSub(double[][] a, double[][] b, double[][] c)
{
if (a == null || b == null || (a.Length != b.Length) || (a[0].Length != b[0].Length))
return;
for (int i = 0; i < a.Length; i++)
{
for (int k = 0; k < a[0].Length; k++)
{
c[i][k] = a[i][k] - b[i][k];
}
}
}
//矩阵乘法
public static void MatrixMul(double[][] a, double[][] b,double[][] c)
{
if (a == null || b == null || a[0].Length != b.Length)
return;
for (int i = 0; i < a.Length; i++)
{
for (int k = 0; k < b[0].Length; k++)
{
c[i][k] = 0;
for (int l = 0; l < a[0].Length; l++)
{
c[i][k] += (a[i][l] * b[l][k]); //a矩阵i行所有元素 * b矩阵j行所有元素之和 = 新的矩阵一个元素
}
}
}
}
public static void MatrixLog(double[][] c)
{
for (int i = 0; i < c.Length; i++)
{
for (int k = 0; k < c[i].Length; k++)
{
Console.Write(c[i][k] + " ");
}
Console.WriteLine();
}
}
}
}
![image image]()