gpt4 book ai didi

java - 使用 ejml(或其他 Java 库)的矩阵索引

转载 作者:搜寻专家 更新时间:2023-10-30 23:01:37 25 4
gpt4 key购买 nike

我正在使用 ejml 库在 Java 中编写数学算法。我认为它非常有用,但我需要知道是否有快速模式(如 print())来打印带索引的矩阵。示例:

    1    2
1 0.00 0.01
2 0.03 0.54
3 3.45 7.88
4 2.24 5.66

否则,您是否知道其他旨在实现此目的的库?

最佳答案

看看 MatrixIO 类。它有超过 10 种不同的 print(...) 方法,适用于各种矩阵。尽管不会打印任何索引,但您可以根据需要覆盖所需的方法。

另一方面,自定义实现应该是相当简单的算法。一些接受各种矩阵的通用方法应该就足够了。

这是一个带注释的工作示例:

代码

public class MatrixWithIndices {

public static void main(String[] args) {
SimpleMatrix simpleMatrix = SimpleMatrix.random_DDRM(5, 5, 1, 9, new Random());

printMatrixWithIndices(simpleMatrix.getDDRM(), 5, 5);
}

public static void printMatrixWithIndices(DMatrix matrix, int numChar, int precision) {
String format = "%" + numChar + "." + precision + "f "; // default format

StringBuilder columnIndexes = new StringBuilder();
columnIndexes.append(" "); //skips first 4 chars

// Append column indices
for (int i = 0; i < matrix.getNumCols(); i++) {
columnIndexes.append(i + 1);

// Print spaces till next column
for (int j = 0; j < String.format(format, matrix.get(0, i)).length() - 1; j++) {
columnIndexes.append(" ");
}
}

// Print column indices
System.out.println(columnIndexes.toString());

// Print horizontal dotted line
System.out.println(" " + columnIndexes.toString().replaceAll(".", "-").substring(3));

// Print rows
for (int y = 0; y < matrix.getNumRows(); ++y) {

// Prints row's index with 'border' (vertical line)
System.out.print((y + 1) + " | ");

// Print matrix values
for (int x = 0; x < matrix.getNumCols(); ++x) {
System.out.printf(format, matrix.get(y, x));
}

// Breaks line
System.out.println();
}
}
}

输出

    1       2       3       4       5       
-----------------------------------------
1 | 7.16880 6.12461 3.67458 8.26479 2.07274
2 | 1.73381 6.81084 7.52687 3.40099 4.50719
3 | 2.56602 8.93279 3.83817 7.26837 2.54689
4 | 6.17946 2.56854 6.42016 3.85734 5.58872
5 | 5.89330 4.50916 1.15128 8.49580 6.02326

它远非完美。对于较大的值,格式化会中断,但它应该会给您一个良好的开端。

GitHub 要点:https://gist.github.com/MSBlastt/7c4f3e25b8bed74fac90b6e0ef2f8e7a

关于java - 使用 ejml(或其他 Java 库)的矩阵索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50271875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com