Java实现矩阵相乘
package com. company;
public class Matrix {
public int row;
public int col;
public double [ ] [ ] data;
Matrix ( double [ ] [ ] array) {
this . row= array. length;
this . col= array[ 0 ] . length;
this . data= new double [ row] [ col] ;
for ( int i= 0 ; i< row; i++ ) {
System. arraycopy ( array[ i] , 0 , this . data[ i] , 0 , col) ;
}
}
public Matrix multiply ( Matrix B) {
Matrix C= new Matrix ( new double [ this . row] [ B. col] ) ;
for ( int A_row= 0 ; A_row< this . row; A_row++ ) {
for ( int B_col= 0 ; B_col< B. col; B_col++ ) {
double sum = 0d ;
for ( int A_col = 0 ; A_col < this . col; A_col++ ) {
sum += this . data[ A_row] [ A_col] * B. data[ A_col] [ B_col] ;
}
C. data[ A_row] [ B_col] = sum;
}
}
return C;
}
@Override
public String toString ( ) {
String result= "[\n" ;
for ( int i= 0 ; i< this . row; i++ ) {
result+= "[" ;
for ( int j= 0 ; j< this . col; j++ ) {
result+= String. format ( "%.3f " , this . data[ i] [ j] ) ;
}
result+= "]\n" ;
}
result+= "]" ;
return result;
}
}