Java读取mat文件
概述
使用ujmp中的jmatio模块读取.mat文件到java程序中。
其实,ujmp主要是在模块core中实现了矩阵运算,其余模块都是复用了已有的开源库。模块jmatio是复用了已有的JMatIo,对这个读取mat文件到java程序的库做了一层封装。从ujmp的官网(https://ujmp.org/)下载ujmp的jar包,但是这一个jar包并不能读取mat文件(虽然jar包内有jmatio模块),还需要下载一个JMatIo的jar包(http://pan.baidu.com/s/1nuMMqvB)。将两个jar包都加入到工程中才可以从mat文件中顺利读取数据到java程序中。
添加jar包到工程
在创建的工程中新建一个lib文件夹,将以上两个jar包拷贝到此文件夹中,必须要拷贝到项目中。比如,我之前是将两个jar包放在桌面上,但是当把jar包删除或移动之后,程序就不能运行了,很简单的道理。
接下来就是将两个jar包添加到工程中,以便在程序中使用这两个包中定义的类。
读取mat文件的代码
1 /** 2 * Created by hfz on 2015/12/22. 3 */ 4 import org.ujmp.jmatio.ImportMatrixMAT; 5 import org.ujmp.core.Matrix; 6 import java.io.File; 7 import java.io.IOException; 8 public class test{ 9 public static void main(String[] args)throws IOException{ 10 //相对路径的根目录是当前工程的目录(C:\Users\hfz\Desktop\test)。另外相对路径的起始处无“/” 11 ImportMatrixMAT test=new ImportMatrixMAT(); 12 File file=new File("data/A.mat"); 13 Matrix testMatrix=test.fromFile(file); 14 testMatrix.showGUI(); 15 System.out.println("ss"); 16 } 17 18 19 }
另外一种更简单的方式
更简单的方式就是直接使用jmatio库从.mat文件读取数据到内存中,并将其转化为二维数组的形式,代码如下:
import com.jmatio.io.MatFileReader; import com.jmatio.types.MLArray; import com.jmatio.types.MLDouble; MatFileReader read = new MatFileReader("data/totalDataSet.mat"); MLArray mlArray=read.getMLArray("img");//mat存储的就是img矩阵变量的内容 MLDouble d=(MLDouble)mlArray; double[][] matrix=(d.getArray());//只有jmatio v0.2版本中才有d.getArray方法
jmatio下载:http://pan.baidu.com/s/1nuMMqvB
参考:
http://www.programcreek.com/java-api-examples/index.php?api=com.jmatio.io.MatFileReader
https://www.kaggle.com/c/decoding-the-human-brain/forums/t/7862/using-jmatio/65560