Java程序設計(七)----矩陣(對矩陣操作的對象)

/* (程序頭部註釋開始)

/* (程序頭部註釋開始)
* 程序的版權和版本聲明部分
* Copyright (c) 2012, 煙臺大學計算機學院學生
* All rights reserved.
* 文件名稱:

* 作 者: 劉鎮
* 完成日期: 2012 年 10 月 09 日
* 版 本 號: 2.007

* 對任務及求解方法的描述部分
* 輸入描述: ......

* 問題描述:封裝一類對矩陣操作的對象,該類對象能夠對矩陣進行運算,如矩陣中數據的位置變換功能、矩陣的加法功能、矩陣的乘法功能

* 程序輸出: ......

* 程序頭部的註釋結束
*/

 

MatrixOperation.java:

 

 

 

package lz_4w;

public class MatrixOperation extends Matrix
{	
	public void changeMatrix(Matrix m, int column_1, int row_1, int column_2, int row_2)
	{
		int t = 0;
		
		t = m.M[column_1][row_1];
	    m.M[column_1][row_1] = m.M[column_2][row_2];
	    m.M[column_2][row_2] = t;
	}
	
	public void MatrixPlus(Matrix m, Matrix n)
	{
		int column = m.M.length;
		int row = n.M[0].length;
		int N = n.M.length;
		
		if(m.M[0].length != n.M.length)
		{
			System.out.println("不能計算矩陣乘法!");
			return ;
		}
	
		int[][] c = new int[column][row];
		
		for(int i = 0; i < column; ++i)
		{
			for(int j = 0; j < row; ++j)
			{
				int total = 0;
				for(int k = 0; k < N; ++k)
				{
					total += m.M[i][k] * n.M[k][j];
				}
				
				c[i][j] = total;
			}
		}
		
		for(int i = 0; i < column; ++i)
		{
			for(int j = 0; j < row; ++j)
			{
				System.out.print(c[i][j] + "\t");
			}
			
			System.out.println();
		}
		
		System.out.println();
	}

	public void MatrixAdd(Matrix m, Matrix n)
	{
		if((m.M.length != n.M.length) || (m.M[0].length != n.M[0].length))
		{
			System.out.println("不能計算兩矩陣加法!");
			return ;
		}
		
		int column = m.M.length;
		int row = m.M[0].length;
		int[][] c = new int[column][row];
		
		for(int i = 0; i < column; ++i)
		{
			for(int j = 0; j < row; ++j)
			{
				c[i][j] = m.M[i][j] + n.M[i][j];
			}
		}
		
		for(int i = 0; i < column; ++i)
		{
			for(int j = 0; j < row; ++j)
			{
				System.out.print(c[i][j] + "\t");
			}
			
			System.out.println();
		}
		
		System.out.println();
	}
}


 

 

 

測試類:

 

package lz_4w;

public class Test_Matrix {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		Matrix m = new Matrix(8, 8, 10);
		Matrix n = new Matrix(8, 8, 5);
		MatrixOperation M = new MatrixOperation();
		
		m.setM(3, 2, 60);
		n.setM(5, 4, 40);
		m.displayMatrix();
		n.displayMatrix();
		
	    M.changeMatrix(m, 2, 2, 1, 1);
		M.changeMatrix(n, 3, 3, 2, 2);
		M.MatrixAdd(m, n);
		M.MatrixAdd(m, n);
	}

}


 

 

 

成果展示:

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章