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

标签 java math matrix ejml

我正在使用 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/

相关文章:

java - 无法使用现有解决方案使 Fragment 中的 onClick 方法正常工作

internet-explorer-8 - dximagetransform.matrix,在 IE 8 标准模式下绝对定位不旋转的子元素

java - 代理无法在 webDriver 中的 chromeOptions 中与 Java 中的 selenium 一起工作

java - 如何获取 "-"(破折号)前后的文本

java - 无法正确退出或完成我的应用程序 android( Activity )

javascript - 使用 CSS3 变换 :rotate in IE origin problem

iphone - 如何计算X秒内的数据包数量?

python - 10位数字和日期时间有什么关系

opencv - 在opencv中快速转置3D矩阵

matlab - 在matlab/octave中通过二维索引访问3维矩阵