日撸代码300行:第31天(整数矩阵及其运算)

代码来自闵老师”日撸 Java 三百行(31-40天)“,链接:https://blog.csdn.net/minfanphd/article/details/116975772

package matrix;

import java.util.*;

import javax.security.auth.kerberos.KerberosKey;
import javax.xml.crypto.Data;

/**
 * Integer matrix. For efficiency we do not define ObjectMatrix. 
 * One can revise it to obtain DoubleMatrix.
 * 
 * @author WX873
 *
 */

public class IntMatrix {
	/**
	 * The data
	 */
	int[][] data;
	
	/**
	 * *************************************
	 * The first constructor
	 * 
	 * @param paraRows
	 *            The number of rows.
	 * @param paraColumns
	 *            The number of columns.
	 * *************************************
	 */
	public IntMatrix(int paraRows, int paraColumns) {
		// TODO Auto-generated constructor stub
		data = new int[paraRows][paraColumns];
	}//of first constructor
	
	/**
	 * *************************************
	 * The second constructor.
	 * 
	 * @param paraMatrix
	 *            The given matrix.
	 * *************************************
	 */
	public IntMatrix(int[][] paraMatrix) {
		// TODO Auto-generated constructor stub
		data = new int[paraMatrix.length][paraMatrix[0].length];
		
		//Copy the data.
		for (int i = 0; i < paraMatrix.length; i++) {
			for (int j = 0; j < paraMatrix[0].length; j++) {
				data[i][j] = paraMatrix[i][j];
			}//of for j
		}//of for i
	}//of the second constructor
	
	/**
	 * ****************************************
	 * The third constructor.
	 * ****************************************
	 */
	public IntMatrix(IntMatrix paraMatrix) {
		// TODO Auto-generated constructor stub
		this(paraMatrix.getData());
	}//The third constructor 
	
	/**
	 * ****************************************
	 * Get Identity Matrix.
	 * @param paraRows  The given rows.
	 * @return
	 * ****************************************
	 */
	public static IntMatrix getIdentityMatrix(int paraRows) {
		IntMatrix resultMatrix = new IntMatrix(paraRows, paraRows);
		
		for (int i = 0; i < paraRows; i++) {
			//According to access control, resultMatrix.data can be visited directly.
			resultMatrix.data[i][i] = 1;
		}//of for i
		return resultMatrix;
	}//of getIdentityMatrix
	
	/**
	 * **********************************************************************
	 * overrides the method claimed in Object, the superclass of any class.
	 * **********************************************************************
	 */
	public String toString() {
		return Arrays.deepToString(data);
	}//of toString
	
	/**
	 * *************************************
	 * Get my data. Warning, the reference to the data
	 *  instead of a copy of the data is returned.
	 * @return  The data matrix.
	 * *************************************
	 */
	public int[][] getData() {
		return data;
	}//of getData
	
	/**
	 * *************************************
	 * @return  The number of rows.
	 * *************************************
	 */
	public int getRows() {
		return data.length;
	}//of getRows
	
	/**
	 * *************************************
	 * @return  The number of columns.
	 * *************************************
	 */
	public int getColumns() {
		return data[0].length;
	}//of getColumns
	
	/**
	 * ***************************************************
	 * Set the value of one element.
	 * @param paraRow     The row of the element.
	 * @param paraColumn  The column of the element.
	 * @param paraValue   The new value.
	 * ***************************************************
	 */
	public void setValue(int paraRow, int paraColumn, int paraValue) {
		data[paraRow][paraColumn] = paraValue;
	}//of setValue
	
	/**
	 * **************************************************
	 * Get the value of one element.
	 * @param paraRow       The row of the element.
	 * @param paraColumn    The column of the element.
	 * @return
	 * **************************************************
	 */
	public int getValue(int paraRow, int paraColumn) {
		int tempResultValue;
		tempResultValue = data[paraRow][paraColumn];
		return tempResultValue;
		
	}//of getValue
	
	/**
	 * **************************************************
	 * Add another matrix to me.
	 * @param paraMatrix   The other matrix.
	 * @throws Exception   Whether the rows and columns of the two arrays match?
	 * **************************************************
	 */
	public void add(IntMatrix paraMatrix) throws Exception {
		// Step 1. Get the data of the given matrix.
		int[][] tempData = paraMatrix.getData();
		
		// Step 2. Size check.
		if (data.length != tempData.length) {
			throw new Exception("Cannot add matrices. Rows not match: " + data.length + " vs. "
					+ tempData.length + ".");
		}//of if
		
		if (data[0].length != tempData[0].length) {
			throw new Exception("Cannot add matrices. columns not match: " + data.length + " vs. "
					+ tempData.length + ".");
		}//of if
		
		// Step 3. Add to me.
		for (int i = 0; i < data.length; i++) {
			for (int j = 0; j < data[0].length; j++) {
				data[i][j] += tempData[i][j];
			}//of for j
		}//of for i
	}//of add
	
	/**
	 * *****************************************************
	 * Add two existing matrices.
	 * @param paraMatrix1   The first matrix.
	 * @param paramatrix2   The second matrix.
	 * @return              A new matrix.
	 * @throws Exception
	 * *****************************************************
	 */
	public static IntMatrix add(IntMatrix paraMatrix1, IntMatrix paramatrix2) throws Exception {
		// Step 1. Clone the first matrix.
		IntMatrix ResultMatrix = new IntMatrix(paraMatrix1);
		
		//Add the second one.
		ResultMatrix.add(paramatrix2);
		
		return ResultMatrix;
	}//of add
	
	public static IntMatrix multiply(IntMatrix paraMatrix1, IntMatrix paraMatrix2) throws Exception{
		// Step 1. Check size.
		int[][] tempData1 = paraMatrix1.getData();
		int[][] tempData2 = paraMatrix2.getData();
		if (tempData1[0].length != tempData2.length) {
			throw new Exception("Cannot multiply matirces: " + tempData1[0].length + " VS. " 
					+ tempData2.length);
		}//of if
		
		// Step 2. Allocate space.
		int[][] resultData = new int[tempData1.length][tempData2[0].length];
		
		// Step 3. Multiply.
		for (int  i = 0;  i < tempData1.length;  i++) {
			for (int j = 0; j < tempData2[0].length; j++) {
				for (int k = 0; k < tempData2.length; k++) {
					resultData[i][j] += tempData1[i][k] * tempData2[k][j];
				}//of for k
			}//of for j
		}//of for i
		
		// Step 4. Construct the matrix object.
		IntMatrix resultMatrix = new IntMatrix(resultData);
		System.out.println(Arrays.deepToString(resultData));
		return resultMatrix;
	}//of multiply
	
	/**
	 * **********************************************
	 * The entrance of program.
	 * @param args   Not used now.
	 * **********************************************
	 */
	public static void main(String args[]) {
		IntMatrix tempMatrix = new IntMatrix(3, 3);
		tempMatrix.setValue(0, 1, 1);
		tempMatrix.setValue(1, 0, 1);
		tempMatrix.setValue(1, 2, 1);
		tempMatrix.setValue(2, 1, 1);
		System.out.println("The original matrix is: " + tempMatrix);
		
		IntMatrix tempMatrix2 = null;
		try {
			tempMatrix2 = IntMatrix.multiply(tempMatrix, tempMatrix);
		} catch (Exception ee) {
			// TODO: handle exception
			System.out.println("ee");
		}//of try
		System.out.println("The square matrix2 is: " + tempMatrix2);
		
		IntMatrix tempMatrix3 = new IntMatrix(tempMatrix2);
		IntMatrix tempMatrix4 = null;
		try {
			tempMatrix3.add(tempMatrix);
			tempMatrix4 = add(tempMatrix, tempMatrix3);
		} catch (Exception ee) {
			// TODO: handle exception
			System.out.println("ee");
		}//of try
		System.out.println("The matrix3 is: " + tempMatrix3);
		System.out.println("The matrix2 now is: " + tempMatrix4);
	}//of main

}//of IntMatrix

今天的难点在矩阵相乘,矩阵相乘是三层for循环。想了很久才想明白,应该是先循环第一个矩阵的行,再循环第二个矩阵的列,最后一个循环是对应数相乘(循环的是第二个矩阵的行)。刚开始运行一直报错,想了很久三层for循环,把三层for循环想明白了,调整了之后发现还是运行错误。最终发现是resultData[i][j] += tempData1[i][k] * tempData2[k][j]; 写成了resultData[i][j] = tempData1[i][k] * tempData2[k][j]; 也就是说矩阵对应元素相乘了之后没有相加。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值