Chinaunix首页 | 论坛 | 博客
  • 博客访问: 107614
  • 博文数量: 106
  • 博客积分: 2025
  • 博客等级: 大尉
  • 技术积分: 1165
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-06 12:51
文章分类

全部博文(106)

文章存档

2012年(106)

我的朋友

分类: Java

2012-05-08 17:05:45

两个矩阵相乘的算法之java

 

import java.util.Scanner;

public class Matrix {
public double[][] create() {
Scanner sc = new Scanner(System.in) ;
System.out.print("
请输入矩阵的行高:");
int a = sc.nextInt() ;
System.out.print("
请输入矩阵的列宽:");
int b = sc.nextInt() ;
double[][] x = new double[a][b] ;
for(int i=0;ifor(int j=0;jSystem.out.print("
请输入元素x["+i+"]["+j+"]的值:" );
x[i][j] = sc.nextDouble() ;
}
}
return x ;
}
public double[][] multiply(double[][] x,double[][] y){
double[][] result = null ;
int a = x[0].length ;
int b = y.length ;
if(a != b){
System.out.println("
输入的维数不匹配,不能进行运算");
}else{
int c = x.length ;
int d = y[0].length ;
result = new double[c][d] ;
for(int i=0;ifor(int j=0;jdouble sum = 0 ;
for(int k=0;ksum += x[i][k]*y[k][j] ;
}
result[i][j] = sum ;
}
}
}
return result ;
}
public void print(double[][] x){
System.out.println("
矩阵为:");
for(int i=0;ifor(int j=0;jSystem.out.print(x[i][j] + " ") ;
}
System.out.println();
}
}
}


class TestMatrix {
public static void main(String[] args) {
Matrix m = new Matrix() ;
//double[][] x = {{1,2},{3,2}} ;
//double[][] y = {{1,2,1},{2,3,3}} ;
System.out.println("
创建第一个数组:") ;
double[][] x = m.create() ;
m.print(x) ; //
用来验证输入的是否和你一致,没什么作用
System.out.println("
创建第二个数组:");
double[][] y = m.create() ;
m.print(y) ; //
用来验证输入的是否和你一致,没什么作用
double[][] result = m.multiply(x, y) ;
if(result == null){
return ; //
如果输入的矩阵不能运算就不输出结果了。
}
m.print(result) ;
}
}

 

阅读(421) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~