Mike
Mike

Reputation: 71

How to import .dat file into Matlab?

i have one file (name.dat) which is binary data, it has 12 lines of header, then just one column of 10^6 floating data points.

I searched that in Matlab I can do

fid=fopen('name.dat','r');
A= fscanf(fid, '%f');
fclose(fid);

When run the three lines of code above, and A is empty; it is wired.

Can you help me out of this ?

Thanks

Upvotes: 2

Views: 78300

Answers (2)

Mike
Mike

Reputation: 71

Finally, I figure it out. when I open my .dat file with text editor, it has headerlines, and data part. I can see the header(ASCII), but the data part is random machine code, which means it is binary data, I also know it is floating point.

so instead of using "textscan or fscan", I use "fread" function in matlab to load the data.

Before loading into matlab, I deleted the header lines, if not deleted, the size of the data loaded is different and wrong.

fid=fopen('name.dat','rt');
A = fread(fid,'*float32');
fclose(fid);

A is the final array data.

Upvotes: 5

Amro
Amro

Reputation: 124563

Here is an example using the TEXTSCAN function:

name.dat

header line 1
header line 2
0.81428
0.24352
0.92926
0.34998
0.1966
0.25108
0.61604
0.47329
0.35166
0.83083

MALTAB

fid = fopen('name.dat','rt');
A = textscan(fid, '%f', 'HeaderLines',2);
A = A{1};
fclose(fid);

A now is vector with the ten numbers

Upvotes: 2

Related Questions