矩阵是工程设计中经常使用的数学工具。
矩阵的运算主要有矩阵加、矩阵减、矩阵乘、矩阵转置、矩阵求逆等。
矩阵用两维数组处理最为方便。
二维数组存储结构。
package org.lixiyuan.juzheng;
import java.util.Random;
public class Mymtrix {
public int[][] mtrix;
public Random random=new Random();
/**
* 默认生成3*3的
*/
public Mymtrix(){
mtrix=new int[3][3];
for (int i = 0; i <mtrix.length; i++) {
for (int j = 0; j <mtrix[i].length; j++) {
mtrix[i][j]=random.nextInt(100);
}
}
}
public Mymtrix(int n){
mtrix=new int[n][n];
for (int i = 0; i <mtrix.length; i++) {
for (int j = 0; j <mtrix[i].length; j++) {
mtrix[i][j]=random.nextInt(100);
}
}
}
public Mymtrix(int n,int m){
mtrix=new int[n][m];
for (int i = 0; i <mtrix.length; i++) {
for (int j = 0; j <mtrix[i].length; j++) {
mtrix[i][j]=random.nextInt(100);
}
}
}
public Mymtrix(int[][]mytrix){
this.mtrix=mytrix;
}
public int[][] getMymtrix(){
return this.mtrix;
}
public void print(){
for (int i = 0; i < mtrix.length; i++) {
for (int j = 0; j < mtrix[i].length; j++) {
System.out.print(mtrix[i][j]+" ");
}
System.out.println();
}
}
/**
* 判断一个矩阵是不是上三角矩阵
*/
public boolean isShangSanJiao(){
for (int i = 0; i < mtrix.length; i++) {
for (int j = 0; j <i; j++) {
System.out.println(mtrix[i][j]);
if(mtrix[i][j]!=0){
return false;
}
}
}
return true;
}
/**
* 判断一个矩阵是不是下三角
* @return
*/
public boolean isXiaSanJiao(){
for (int i =0; i<mtrix.length; i++) {
for (int j = i+1; j<mtrix.length; j++) {
if(mtrix[i][j]!=0){
System.out.println(mtrix[i][j]);
return false;
}
}
}
return true;
}
}
测试类:
package org.lixiyuan.juzheng;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
Mymtrix m1 = new Mymtrix();
Mymtrix m2 = new Mymtrix(4);
System.out.println("m1矩阵:");
m1.print();
System.out.println("m2矩阵:");
m2.print();
Mymtrix m3=new Mymtrix( new int[][]{
{1,0,0,0},
{2,3,0,1},
{4,5,6,0},
{7,8,6,10}
});
m3.print();
System.out.println(m3.isXiaSanJiao());
// Mymtrix m4=new Mymtrix( new int[][]{
// {1,1,1,1},
// {0,3,1,1},
// {0,0,6,1},
// {0,0,0,10}
// });
// m4.print();
// System.out.println(m4.isShangSanJiao());
}
}
输出结果:
m1矩阵:
28 47 42
47 22 86
56 78 99
m2矩阵:
42 67 97 47
22 3 43 44
80 19 5 42
28 64 49 24
1 0 0 0
2 3 0 1
4 5 6 0
7 8 6 10
1
false