Matlab: Read matrix data from a file

In matlab, there are many commands we can use to read data from a file, such as fscanf, fread, dlmread, load, textscan, fgetl, fgets etc.

Sometimes, I use fscanf, which can read a certain number of elements in different format into variables, such as integer, double, character etc.

Now if I can want to read a numeric matrix from a file. If there are no characters, then many commands such as fscanf, dlmread and load can work.

If there is a header which are characters. But you just want to read the numeric matrix. For example

x     y     z

1     2     3

4     5     6

In this case, load can’t work, because when load is used to load a ASCII file, it can only read numeric data.

dlmread works, using:

M = dlmread(FILENAME,DELIMITER,ROW,COLUMN)

Row and column starts from 0. Here ROW should be 1, COLUMN is 0.

fscanf can also work. But we need ignore the first row. So what I do is:

fid = fopen(‘FILENAME’,’r’);

h = fscanf(fid,’%s’,3);

M = fscanf(fid,’%f %f %f’,[3 2]);

Note: load and dlmread will generate a matrix that has the same form as in the text file. But fscanf will be the transpose of it, since it read a row (different columns) from the text file into the 1st dimension of the matrix which will be a column (different rows).

In this case, dlmread will give you

1 2 3

4 5 6

While fscanf will give you

1   4

2   5

3   6

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: