矩阵类:
using System.Text;
namespace matrix.MatrixDemo
{
public class Matrix
{
//矩阵的阶数 n行,m列
private int n;
private int m;
//一维数组
private int[,] table;
public Matrix(int n = 0)
{
this.table = null;
if (n > 0)
{
this.n = n;
this.m = n;
this.table = new int[n, m];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
this.table[i, j] = 0;
}
}
}
}
public Matrix(int[,] matrix1, int n, int m)
{
if (n > 0 && m > 0 && matrix1 != null)
{
this.n = n;
this.m = m;
this.table = new int[n, m];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
this.table[i, j] = matrix1[i, j];
}
}
}
}
public Matrix(Matrix matrix1)
{
this.n = matrix1.getRow();
this.m = matrix1.getColumn();
this.table = new int[n,m];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
this.table[i, j] = matrix1.get(i,j);
}
}
}
public int getRow() {
return n;
}
public int getColumn() {
return m;
}
public int get(int i, int j){
if(i>=0 && i<n && j>=0 && j<m){
return this.table[i,j];
}else{
return -32767;
}
}
public bool set(int i, int j, int k) {
if(i>=0 && i<n && j>=0 && j<m) {
this.table[i,j] = k;
return true;
}else {
return false;
}
}
public static Matrix operator +(Matrix matrix1, Matrix matrix2){
Matrix matrix3 = new Matrix(matrix1);
int row = matrix1.getRow();
int column = matrix1.getColumn();
for(int i=0;i<row;i++){
for(int j=0;j<column;j++){
int value = matrix1.get(i,j) +matrix2.get(i,j);
matrix3.set(i,j,value);
}
}
return matrix3;
}
public override string ToString() {
StringBuilder sb = new StringBuilder();
sb.Append("矩阵:\n");
for(int i = 0;i<n;i++){
for(int j = 0;j<m;j++){
sb.Append(this.get(i,j));
sb.Append(" ");
}
sb.Append("\n");
}
return sb.ToString();
}
}
}
调用方法类:
using System;
using matrix.MatrixDemo;
namespace matrix
{
class Program
{
static void Main(string[] args)
{
int [,] arr1 = {
{1,2,3,4},
{0,1,0,0},
{0,0,1,0},
{0,0,0,1}
};
int [,] arr2 = {
{0,0,0,1},
{0,0,1,0},
{0,1,0,0},
{1,0,0,0}
};
Matrix matrix1 = new Matrix(arr1, 4, 4);
Matrix matrix2 = new Matrix(arr2, 4, 4);
Matrix matrix3 = matrix1 + matrix2;
Console.Write(matrix3);
}
}
}
程序输出如下: