java矩阵加减乘除_Java编写一个程序实现矩阵的运算加减乘除,(并对其中的异常进行处理)...

展开全部

/**

* 矩阵:由62616964757a686964616fe4b893e5b19e31333337626237 m × n 个数Aij排成的m行n列的数表称为m行n列的矩阵,简称m × n矩阵

* 说白了就是一个二维数组,下面的程序用整形作为数据类型,其他类型运算大同小异

*

*/

public class MatrixUtils {

/**

* 矩阵运算:加(减法与之类似)

*/

public static int[][] matrixAdd(int[][] addend, int[][] summand) {

if (addend == null || addend.length == 0) {

throw new IllegalArgumentException("addend matrix is empty!");

}

if (summand == null || summand.length == 0) {

throw new IllegalArgumentException("summand matrix is empty!");

}

//矩阵加减要求两个矩阵类型一致,即行列数相同

int row = addend.length;

int col = addend[0].length;

if (row != summand.length || col != summand[0].length) {

throw new IllegalArgumentException("summand and summand not the same type!");

}

int[][] sum = new int[row][col];

for (int i = 0; i 

for (int j = 0; j 

sum[i][j] = addend[i][j] + summand[i][j];

// sum[i][j] = addend[i][j] - summand[i][j]; //减法

}

}

return sum;

}

/**

* 矩阵运算:乘法,没找到除法的运算规则

*/

public static int[][] matrixMultiply(int[][] addend, int[][] summand) {

if (addend == null || addend.length == 0) {

throw new IllegalArgumentException("addend matrix is empty!");

}

if (summand == null || summand.length == 0) {

throw new IllegalArgumentException("summand matrix is empty!");

}

//两个矩阵的乘法仅当第一个矩阵A的列数和另一个矩阵B的行数相等时才能定义。如A是m×n矩阵和B是n×p矩阵,它们的乘积C是一个m×p矩阵

int row = addend.length;

int col = summand[0].length;

if (addend[0].length != summand.length) {

throw new IllegalArgumentException("summand and summand not the same type!");

}

int[][] sum = new int[row][col];

for (int i = 0; i 

for (int j = 0; j 

for (int z = 0; z 

sum[i][j] += addend[i][z] * summand[z][j];

System.out.println("sum[" + i+  "]["+ j+"]= " + sum[i][j]);

}

}

}

return sum;

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值