我想用for循环实现一个矩阵。为了创建矩阵,我使用了Jama matrix包。
以下是我的代码
import Jama.Matrix;
public class Matrixnonsym {
public static void main(String args[]) {
Matrix Mytest=new Matrix(5,5);
for(int i=0; i<4; i++) {
Mytest.set(i,i,1);
Mytest.set(i+1,i,1);
}
Mytest.print(9,6);
}
}下面是我的输出:
1.000000 0.000000 0.000000 0.000000 0.000000
1.000000 1.000000 0.000000 0.000000 0.000000
0.000000 1.000000 1.000000 0.000000 0.000000
0.000000 0.000000 1.000000 1.000000 0.000000
0.000000 0.000000 0.000000 1.000000 0.000000没有编译错误或运行时错误。困难在于如何使(0,0)单元格的值为2?由于这个矩阵是使用for循环构造的,所以所有的值都是对称构造的。那么我如何才能使一个单元格具有不同的值呢?
期望输出:
2.000000 0.000000 0.000000 0.000000 0.000000
1.000000 1.000000 0.000000 0.000000 0.000000
0.000000 1.000000 1.000000 0.000000 0.000000
0.000000 0.000000 1.000000 1.000000 0.000000
0.000000 0.000000 0.000000 1.000000 0.000000发布于 2018-08-11 03:11:33
您可以在for循环中使用if条件,以使特定单元格具有不同的值。
import Jama.Matrix;
public class Matrixnonsym {
public static void main(String args[]){
Matrix Mytest=new Matrix(5,5);
for(int i=0;i<4;i++){
if(i == 0){
Mytest.set(i,i,2);
}
Mytest.set(i,i,1);
Mytest.set(i+1,i,1);
}
Mytest.print(9,6);
}
}发布于 2018-08-11 03:07:40
我以前从未使用过Jama,但我认为在Javadoc中您可以这样做:
import Jama.Matrix;
public class Matrixnonsym {
public static void main(String args[]){
Matrix Mytest=new Matrix(5,5);
for(int i=0;i<4;i++){
Mytest.set(i,i,1);
Mytest.set(i+1,i,1);
}
Mytest.set(0, 0, 2.0)
Mytest.print(9,6);
}
}发布于 2018-08-11 03:10:50
import Jama.Matrix;
public class Matrixnonsym {
public static void main(String args[]){
Matrix Mytest=new Matrix(5,5);
for(int i=0;i<4;i++){
if (i==0) {
Mytest.set(i,i,2);
} else {
Mytest.set(i,i,1);
}
Mytest.set(i+1,i,1);
}
Mytest.print(9,6);
}
}https://stackoverflow.com/questions/51792670
复制相似问题