metal
metal

Reputation: 25

Reading data in Matlab from a large textfile

I have a text file containing a large number of rows of data with columns separated by spaces. How can I read in this data with MATLAB? I have tried the following code without success:

fid = fopen('file.txt');

M = textscan(fid, '%f %f %f');

x = M{1};

y = M{2};

z = M{3};

The data is as shown below (the columns are not equally spaced):

4.55686    0.88751    4.71368       0.00000       0.00000   879.7   0.143   1.77  1  1  Iron - Alpha

4.55686    0.88751    4.71368       0.00000       0.00000   879.7   0.143   1.77  1  1  Iron - Alpha

4.55686    0.88751    4.71368       0.00000       0.00000   879.7   0.143   1.77  1  1  Iron - Alpha

4.55686    0.88751    4.71368       0.00000       0.00000   879.7   0.143   1.77  1  1  Iron - Alpha

4.55686    0.88751    4.71368       0.00000       0.00000   879.7   0.143   1.77  1  1  Iron - Alpha

4.55686    0.88751    4.71368       0.00000       0.00000   879.7   0.143   1.77  1  1  Iron - Alpha

Upvotes: 2

Views: 4682

Answers (2)

High Performance Mark
High Performance Mark

Reputation: 78364

First, consider your data file. Each line contains 10 numbers and 3 strings. It would be easy to think that it contains 10 numbers and 1 string, but since a space is used as a delimiter and the characters Iron - Alpha are not enclosed in quotation marks they make 3 strings, not 1.

Next, textscan will only behave itself as you wish if you provide a complete description of the input line in the format specification. For example, the following

 M = textscan(fid, '%f %f %f %f %f %f %f %f %f %f %s %s %s')

works just fine for me. Since you only want the first 5 columns of data, and this reads all the data, you can easily delete the unwanted columns.

If you want or need to avoid reading the unwanted data you'll have to get a little smarter. You can instruct textscan to ignore specific fields like this:

 M = textscan(fid, '%f %f %f %f %f %*f %*f %*f %*f %*f %*s %*s %*s')

which reads only the first 5 fields in each line. The documentation will point you towards ways of refining your reading routine even further.

Upvotes: 3

Yuan
Yuan

Reputation: 1157

Please try dlmread.

data = dlmread('file.txt');

And check if the separator is space. It may contain invisible char '\t'.

Upvotes: 2

Related Questions