user2743
user2743

Reputation: 1513

Reading in data from a text file using textscan in MatLab

I'm trying to read in data from a text file using textscan. The textfile is delimited by 3 spaces and has 100 rows of data and 9 columns. I can get it to return what I think is a 100 x 1 matrix. I'm trying to figure out how to get the code to return a matrix 100 x 9. Below is the code I'm using...

fid = fopen('file.txt','r');
data = textscan(fid, '   %d   %d   %d   %d   %d   %d   %d   %d   %d\n');
disp(data);     %This command outputs [100x1 int32]
fprintf('data is: %s\n', data{1}); %this outputs garbage
fprintf('data is: %s\n', data{2}); %this outputs garbage
fprintf('data is: %s\n', data{3}); %this outputs garbage
fprintf('data is: %s\n', data{4}); %this outputs garbage
fprintf('data is: %s\n', data{5}); %see output below
Columns 1 through 4

[100x1 int32]    [100x1 int32]    [100x1 int32]    [100x1 int32]

Columns 5 through 8

[100x1 int32]    [100x1 int32]    [100x1 int32]    [100x1 int32]

Column 9

[100x1 int32]

fclose(fid);

As you can see I'm getting some what close to what I want when I access data{5}. My end goal is to create a matrix with columns 1-8 and then a column matrix with row 9. Below is how the data is formatted in the text file. There is 3 spaces before the 1st column and 3 spaces delimited between each column after that.

1.2000000e+02   1.0000000e+00   3.2000000e+00   7.2300000e+02   1.7000000e+00   9.0440000e+03   9.6700000e+02   6.8000000e+01   6.4580000e+01

Thanks in advance for any help. I've being messing with the textscan parameters and delimiters for a while with no luck. I'm not familiar with textscan but I've read that I should use it in this case because there are non numeric characters in the data being imported.

Upvotes: 0

Views: 976

Answers (1)

Mohsen Nosratinia
Mohsen Nosratinia

Reputation: 9864

You can use cell2mat to create a matrix from cell elements

matrix1 = cell2mat(data(1:8));
matrix2 = data{9};

Upvotes: 1

Related Questions