Matlab - Importing a .dat file into an array

11,148

You may use textscan. The first call to this function will handle the first line (i.e. get the dimension of your file) and the second call the remaining of your file. The second call uses repmat to declare the format spec: %f, meaning double, repeated nb_col times. The option CollectOutput will concatenate all the columns in a single array. Note that textscan can read the entire file without specifying the number of rows.

The code would be

fileID = fopen('youfile.dat');     %declare a file id

C1 = textscan(fileID,'%s%f%s%f');   %read the first line
nb_col = C1{4};                     %get the number of columns (could be set by user too) 

%read the remaining of the file
C2 = textscan(fileID, repmat('%f',1,nb_col), 'CollectOutput',1);

fclose(fileID);                     %close the connection

In the case where the the number of columns is fixed, you can simply do

fileID = fopen('youfile.dat');
C1 = textscan(fileID,'%s%f%s%f');   %read the first line
im_x = C1{2};                       %get the x dimension 
im_y = C1{4};                       %get the x dimension 

C2 = textscan(fileID,'%f%f%f%f%f%f%*[^\n]', 'CollectOutput',1);
fclose(fileID);

The format specification %*[^\n] skips the remaining of a line.

Share:
11,148
Paul C
Author by

Paul C

Updated on June 04, 2022

Comments

  • Paul C
    Paul C almost 2 years

    I'm still fairly new to Matlab but for some reason the documentation hasn't been all that helpful with this.

    I've got a .dat file that I want to turn into a _ row by 6 column array (the number of rows changes depending on the program that's generating the .dat file). What I need to do is get the dimensions of the image this array will be used to make from the 1st row 2nd column (x dimension) and 1st row 4th column (y dimension). When using the Import Data tool in Matlab, this works properly:

    enter image description here

    However I need the program to do it automatically. If the first line wasn't there, I'm pretty sure I could just use fscanf to put the data in the array, but the image dimensions are necessary.

    Any idea what I need to use instead?