You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何以表格格式打印Apache Commons Math的RealMatrix

解决Apache Commons Math RealMatrix优雅打印的问题

嘿,我懂你现在的烦恼——用Apache Commons Math的RealMatrix处理矩阵后,手动写嵌套循环打印的格式实在太乱糟糟了对吧?别发愁,这个库本身就自带了优雅的打印方案,完全不用自己折腾循环~

下面给你两种实用的解决办法:

方案1:直接用RealMatrix自带的toString()方法

这是最省心的方式,默认就会输出对齐规整的矩阵格式,代码示例如下:

import org.apache.commons.math3.linear.MatrixUtils;
import org.apache.commons.math3.linear.RealMatrix;

public class MatrixPrintDemo {
    public static void main(String[] args) {
        double coord[][] = new double[3][3];
        coord[0][0] = 1d; coord[0][1] = 0d; coord[0][2] = 0d;
        coord[1][0] = 2d; coord[1][1] = 1d; coord[1][2] = 1d;
        coord[2][0] = 3d; coord[2][1] = 2d; coord[2][2] = 0d;

        // 把二维数组转换成RealMatrix对象
        RealMatrix matrix = MatrixUtils.createRealMatrix(coord);

        // 直接打印,格式自动对齐
        System.out.println("coordinates [nó, x, y]");
        System.out.println(matrix);
    }
}

输出效果会是这样的,每一列都整整齐齐:

coordinates [nó, x, y]
1.0  0.0  0.0
2.0  1.0  1.0
3.0  2.0  0.0

方案2:自定义打印格式(按需调整小数位、分隔符)

如果默认格式不符合你的需求,比如想少保留几位小数,或者换个元素分隔符,可以用RealMatrixFormat来定制,代码示例:

import org.apache.commons.math3.linear.MatrixUtils;
import org.apache.commons.math3.linear.RealMatrix;
import org.apache.commons.math3.linear.RealMatrixFormat;
import java.text.DecimalFormat;

public class CustomMatrixPrintDemo {
    public static void main(String[] args) {
        double coord[][] = new double[3][3];
        coord[0][0] = 1d; coord[0][1] = 0d; coord[0][2] = 0d;
        coord[1][0] = 2d; coord[1][1] = 1d; coord[1][2] = 1d;
        coord[2][0] = 3d; coord[2][1] = 2d; coord[2][2] = 0d;

        RealMatrix matrix = MatrixUtils.createRealMatrix(coord);

        // 自定义小数格式(比如只保留整数位)
        DecimalFormat elementFormat = new DecimalFormat("#");
        // 定制矩阵的分隔符和前后缀
        RealMatrixFormat format = new RealMatrixFormat(
                "", "", "", "", "\n", "  " // 前缀、后缀、行前缀、行后缀、行分隔符、元素分隔符
        );

        // 格式化后打印
        System.out.println("coordinates [nó, x, y]");
        System.out.println(format.format(matrix, elementFormat));
    }
}

这段代码的输出会变成整数形式,同样保持对齐:

coordinates [nó, x, y]
1  0  0
2  1  1
3  2  0

为啥不推荐手动循环打印?

你原来写的嵌套循环不仅代码冗余,还很容易出现列不对齐的问题(比如数字位数不一样时,整个矩阵看起来歪歪扭扭),而库自带的打印方法已经帮我们处理了所有对齐细节,输出的矩阵既美观又专业。

内容的提问来源于stack exchange,提问作者Jows

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:06:56