java矩阵类_151-矩阵类
[java]代碼庫import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int r = scan.nextInt();
int c = scan.nextInt();
System.out.println("row:"+r+" column:"+c);
//輸入,修改矩陣的值
Matrix me = new Matrix(r,c);
for(int i = 0; i < r; i++)
{
for(int j = 0; j < c; j++)
{
double a = scan.nextDouble();
me.set(i, j, a);
}
}
r = scan.nextInt();
c = scan.nextInt();
double a = scan.nextDouble();
me.set(--r, --c, a);
System.out.println("after set value:");
me.show();
//打印具體位置上的值
r = scan.nextInt();
c = scan.nextInt();
System.out.print("value on ("+r+","+c+"):");
System.out.printf("%.0f\n",me.get(--r, --c));
//矩陣相加輸出
r = scan.nextInt();
c = scan.nextInt();
Matrix jia = new Matrix(r,c);
for(int i = 0; i < r; i++)
{
for(int j = 0; j < c; j++)
{
a = scan.nextDouble();
jia.set(i, j, a);
}
}
System.out.println("after add:");
(me.add(jia)).show();
//矩陣相乘輸出
r = scan.nextInt();
c = scan.nextInt();
Matrix cheng = new Matrix(r,c);
for(int i = 0; i < r; i++)
{
for(int j = 0; j < c; j++)
{
a = scan.nextDouble();
cheng.set(i, j, a);
}
}
System.out.println("after multiply:");
(me.multiply(cheng)).show();
//矩陣轉置輸出
System.out.println("after transpose:");
(me.transpose()).show();
}
}
class Matrix
{
private int row;//行
private int col;//列
double[][] m;
public Matrix(int a, int b)
{
row = a;
col = b;
m = new double [a][b];
}
void set(int r, int c, double a)
{
m[r][c] = a;
}
double get(int r, int c)
{
return m[r][c];
}
int width()
{
return col;
}
int height()
{
return row;
}
Matrix add(Matrix b)
{
Matrix a = new Matrix(row,col);
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
a.set(i,j, b.get(i,j)+this.m[i][j]);
}
return a;
}
Matrix multiply(Matrix b)
{
Matrix a = new Matrix(row,b.width());
for( int i = 0; i < row; i++)
{
for( int j = 0; j < b.width(); j++)
{
int sum = 0;
for( int k = 0; k < col; k++)
sum += this.get(i,k)*b.get(k, j);
a.set(i, j, sum);
}
}
return a;
}
Matrix transpose()
{
Matrix a = new Matrix(col,row);
for(int i = 0; i < col; i++)
{
for(int j = 0; j < row; j++)
a.set(i,j,this.m[j][i]);
}
return a;
}
void show()
{
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
{
if( j == 0)
System.out.printf("%.0f",this.get(i, j));
else
System.out.printf(" %.0f",this.get(i, j));
}
System.out.println();
}
}
}
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的java矩阵类_151-矩阵类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java捕获异常密码_Java捕获异常的
- 下一篇: vue获取当前月最后一天_只争朝夕,不负