java - 如何在Java中使用for循环时打印非对称值

标签 java matrix logic jama

我想使用for循环实现一个矩阵。为了创建矩阵,我使用了 Jama Matrix Package。

这是我的代码

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

最佳答案

您可以在 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);
}
}

关于java - 如何在Java中使用for循环时打印非对称值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51792670/

相关文章:

java - 使用私钥后如何从内存中清除私钥数据?

java - 带有 tastypie JSON 结果的 JSON 格式错误

R:邻接表到邻接矩阵

c - 为什么这个逻辑/按位运算返回 1?

c# - 减少位顺序逻辑

java - 远程管理接口(interface) : NotBoundException

java - 如何在 Jetty Maven 插件中启用 CachingWebAppClassLoader?

arrays - R 应用数组输出维度

java - 用二进制数填充矩阵,常规和格雷编码

python - 这个 Python 表达式有意义吗?