Java数据结构——整数矩阵及其运算

本文介绍了使用Java实现整数矩阵的加法、乘法以及方阵的幂次运算,包括详细的操作步骤和测试示例。
摘要由CSDN通过智能技术生成

IntMatrix

  • 矩阵相加
	/**
	 * 矩阵相加
	 * @param m1
	 * @param m2
	 * @return
	 */
	public static IntMatrix add(IntMatrix m1, IntMatrix m2) {
   

		// 检查异常
		int r1 = m1.matrix.length;
		int c1 = m1.matrix[0].length;
		int r2 = m2.matrix.length;
		int c2 = m2.matrix[0].length;
		if (r1 != r2) {
   
			throw new RuntimeException("两个矩阵的行高都不相等!");
		}
		if (c1 != c2) {
   
			throw new RuntimeException("两个矩阵的列宽都不相等!");
		}

		// 初始大小
		IntMatrix resultMatrix = new IntMatrix(r1, c1);

		// 计算
		for (int i = 0; i < m1.matrix.length; i++) {
   

			for (int j = 0; j < m2.matrix.length; j++) {
   

				resultMatrix.matrix[i][j] = m1.matrix[i][j] + m2.matrix[i][j];
			}
		}

		return resultMatrix;
	}
  • 矩阵相乘
	/**
	 * 矩阵相乘
	 * @param m1
	 * @param m2
	 * @return
	 */
	public static IntMatrix multiply(IntMatrix m1, IntMatrix m2) {
   

		// 判断是否能够相乘
		if (m2.matrix[0].length != m1.matrix.length) {
   
			throw new RuntimeException("第一个矩阵的列宽不等于第二个矩阵的行高!");
		}

		// 初始resultMatrix的大小
		int r = m1.matrix.length;
		int c = m2.matrix[0].length;
		IntMatrix resultMatrix = new IntMatrix(r, c);

		// 计算
		for (int i = 0; i < m1.matrix.length; i++) {
   

			for (int j = 0; j < m2.matrix.length; j++) {
   

				for (int k = 0; k < m1.matrix[0].length; k++) {
   

					resultMatrix.matr
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

姜满月

鼓励,鼓励,更加努力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值