首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用ejml (或其他Java库)的矩阵索引

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

Stack Overflow用户
提问于 2018-05-10 19:26:41
回答 1查看 445关注 0票数 6

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

代码语言:javascript
复制
    1    2
1  0.00 0.01
2  0.03 0.54
3  3.45 7.88
4  2.24 5.66

否则,您是否知道针对此目的的其他库?

EN

回答 1

Stack Overflow用户

发布于 2018-06-28 18:45:06

看看MatrixIO类。它有超过10种不同的print(...)方法,适用于各种矩阵。尽管不会打印索引,但您可以随意重写所需的方法。

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

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

代码

代码语言:javascript
复制
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();
        }
    }
}

输出

代码语言:javascript
复制
    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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50271875

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档