Search code examples
javamatlabopencvmatmat-file

How can I load / open / read a matlab file *.mat in java?


My code so far (based on this entry) but it doesn't work:

MatFileReader matfilereader = new MatFileReader("C:\\data\\Freebase\\initEmbed.mat");
System.out.println(matfilereader.getData().get(0) + "name: "+matfilereader.getMLArray("words").getSize());
System.out.println("new "+matfilereader.getMLArray("words"));
MLArray words = matfilereader.getMLArray("words");
System.out.println(words.contentToString().substring(0, 100));
MLChar j = (MLChar) matfilereader.getMLArray("words");

My output:

[1x91898  cell array]name: 91898
new [1x91898  cell array]
words = 
    [1x9  char array]   [1x3  char array]   [1x1  char array]   [1x1  char array]   [1x2  char array]   

Exception in thread "main" java.lang.ClassCastException: com.jmatio.types.MLCell cannot be cast to com.jmatio.types.MLChar
    at NTN.Run_NTN.main(Run_NTN.java:91)

How to load the words of this matlab file into a java array?


Solution

  • I don't know anything about matLab, but the exception seems pretty clear. You're casting an MLCell to a a MLChar. "getMLArray" must be returning an MLCell. I would cast to an MLCell first

    MLCell mlCell = (MLCell) matfilereader.getMLArray("words");
    

    And then use whatever methods are available on that type to get the MLChar.