Java矩阵计算库UJMP

前言

Java中矩阵计算库常用的有:ujmp, ejml。
在使用中发现ujmp相对好用些,本文对此进行介绍。

UJMP

全称 Universal Java Matrix Package
官网 https://ujmp.org/


导入maven依赖

必须导入的有

<dependency>
    <groupId>org.ujmp</groupId>
    <artifactId>ujmp-core</artifactId>
    <version>0.3.0</version>
</dependency>

ujmp提供gui,方便可视化。需导入

<dependency>
    <groupId>org.ujmp</groupId>
    <artifactId>ujmp-gui</artifactId>
    <version>0.3.0</version>
</dependency>

UJMP常用方法

创建矩阵

矩阵元素为 数值类型。

Matrix.Factory.rand(rows, cols);  // 创建rows行 cols列的Matrix,元素数值范围[0,1]
Matrix.Factory.randn(rows, cols); // 创建Matirx,元素值服从标准正态分布N(0,1)
Matrix.Factory.zeros(rows, cols); // 创建Matrix,元素值都是0

DoubleMatrix.Factory.zeros(rows, cols); // 指定具体的类型为DoubleMatrix类型,则元素为double型

矩阵元素为 字符串类型

StringMatrix.Factory.zeros(rows, cols);

矩阵内单个元素的get/set

Matrix mat = Matrix.Factory.zeros(5, 4);
mat.setAsDouble(5.0, 0, 0); // 0-based index
mat.getAsDouble(0, 0); // 获取到坐标(0,0)的值
mat.getAsInt(0, 0); // 获取到值,并且转成int格式

同理:

StringMatrix2D stringMatrix2D = StringMatrix.Factory.zeros(2,2);
stringMatrix2D.setAsString("a", 0, 0);
stringMatrix2D.setAsString("b", 0, 1);
stringMatrix2D.setAsString("11", 1, 0);
stringMatrix2D.setAsString("22", 1, 1);

System.out.println(stringMatrix2D);

获取矩阵行或列数值,求均值,标准差,元素替换

IrisMatrix matrix = DenseMatrix.Factory.irisMatrix(); // 获取ujmp自带的iris数据,方便演示

Matrix col0 = matrix.selectColumns(Calculation.Ret.NEW, 0); // 获取matrix的某一列。第1个参数意思是输出的是一个新的矩阵,第2个参指定第几列 这里是第0列
Matrix row1 = matrix.selectRows(Calculation.Ret.NEW, 1); // 获取matrix的某一行。这里是获取第1行。
Matrix select = matrix.select(Calculation.Ret.NEW, new long[]{0,1}, new long[]{1,2}); // 获取指定范围的数据,比如 行下标0-1, 列下标1-2

Matrix mean = matrix.mean(Calculation.Ret.NEW, 0, true);  // 矩阵求均值。第2个参数dimension 0是对列, 1对行,第3个参数为 是否ignoreNaN
Matrix std = matrix.std(Calculation.Ret.NEW, 0, true, true); // 标准差。第2个参数是dimension, 第3个参数是ignoreNaN, 第4个参数为是否考虑贝塞尔校正(当对采样数据进行求std时,往往需要校正)

Matrix matrix1 = matrix.replace(Calculation.Ret.NEW, "Iris-setosa", "0");  // replace操作。把矩阵中元素值为"Iris-setosa"替代为"0"

获取矩阵行数,列数,转置,加减乘求逆,行列式,特征值特征向量

Matrix mat = Matrix.Factory.zeros(5, 5);
mat.getRowCount(); // mat的行数
mat.getColumnCount(); // mat的列数

Matrix transpose = mat.transpose(); // 矩阵转置

Matrix plus = mat.plus(transpose); // 矩阵加法
Matrix minus = mat.minus(transpose); // 矩阵减法
Matrix mtimes = mat.mtimes(transpose); // 矩阵乘法
Matrix times = mat.times(2); // 矩阵elementwise乘法
mat.inv(); // 矩阵求逆

mat.det(); // 矩阵的determinant

Matrix[] eig = mat.eig(); // 输出的eig内有两个元素,分别是特征向量和特征值

GUI

当导入了ujmp-gui依赖后可用。

IrisMatrix matrix = DenseMatrix.Factory.irisMatrix();
matrix.showGUI(); // 将矩阵可视化

参考

https://ujmp.org/

  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值