1

I wrote a Java program to output numeric data to binary .txt file and plan to use Matlab to process that data file.

In the Java program, I used DataOutputStream to write float numbers to data.txt file and test by using DataInputStream to read data.txt what wrote earlier. And I got right result.

    // write {1.0, 2.0, 3.0, 4.0, 5.0, 6.0}
    private void writeFile(Float [] data) throws IOException {
        FileOutputStream fos = new FileOutputStream(fileName);
        DataOutputStream dos = new DataOutputStream(fis);

        for (int i = 0; i < data.length; ++i) {
            dos.writeFloat(data[i]);
        }
        dos.close();
}

//output is {1.0, 2.0, 3.0, 4.0, 5.0, 6.0}
private float[] readFile( String fileName, int size) throws IOException {
    FileInputStream fis = new FileInputStream(fileName);
    DataInputStream dis = new DataInputStream(fis);
    float [] dataArray = new int[size];

    for (int i = 0; i < dataArray.length; ++i) {
        dataArray[i] = dis.reaFloat();
    }
    dis.close();
    return dataArray;
}

However, when I use data.txt file in matlab, I got wrong number.

fid = fopen('data.txt');
data = fread(fid, 'float');
fclose all;

What I got back is:
data =

   1.0e-40 *

   0.4601
   0.0009
   0.2305
   0.4601
   0.5749
   0.6897

So, I doubt that that might be a problem with my convert from binary to float in Matlab. Any recommendation is appreciated.

Or is there any other way to write primitive data from Java and process in Matlab? Thanks.

nghiduong90
  • 107
  • 7

1 Answers1

0

You can write your data to a file in CSV format then import it to Matlab.

If your output file is a CSV file

1.1, 1.2, 1.3                                                                                                      
3.2, 3.3, 4.5

then you can import your data into matlab using either importdata or csvread commands

your_data = importdata('test.txt', ',')
your_data = csvread('test.txt')

If you have a more complicated data format then use textscan. For example, you can parse below data format

"1.1", "1.2", "1.3", "3.2", "3.3", "4.5"

into a cell array using below commands.

buffer = fileread('/tmp/list.txt')
values = textscan(buffer, '"%f"', 'Delimiter', ',')
hungptit
  • 1,414
  • 15
  • 16
  • Thanks for you suggestion. I actually try with csv format by CSVWriter in Java. But data in file is string, like "1.1", "1.2",... And it is hard to process. Can you guide me more detail for output in csv format? – nghiduong90 Apr 23 '16 at 01:00
  • I do not know much about Java so I can't give you a detail instruction. However, you can use MATLAB textscan function to read data from your csv file. – hungptit Apr 25 '16 at 20:04