Reputation: 557
I have a text file which have 5 columns. Here is sample data:
book 1 3 5 7
paper 3 9 0 2
pen 3 1 2 0
pencil 9 0 3 9
The first column contains character and the other columns are just number. The file contains several rows. I am trying to read that .txt as follows;
fileID = fopen('filename.txt');
C = textscan(fileID,'%s %n %n %n %n');
fclose(fileID);
celldisp(C)
It read the column correctly. However, it reads only the first row, and not all. Why it is happening that way? How to do if I want to read all rows and all columns. Thanks
Upvotes: 0
Views: 959
Reputation: 3177
I assume you want to create a cell array in which every cell contains a single element from your text file.
The code you provided so far is correct:
fileID = fopen('filename.txt');
C = textscan(fileID,'%s %n %n %n %n');
fclose(fileID);
However now each cell in C
contains an entire column from your txt file:
where C{1,1}
contains the first column, that are four strings (book, paper, pen, pencil).
Now it is time un "unwrap" such cells using this piece of code:
for i=1:size(C,2)
if(iscell(C{:,i}))
A(:,i)=reshape(C{:,i},length(C{:,i}),1);
else
A(:,i)=num2cell(reshape(C{:,i},length(C{:,i}),1));
end
end
that basically says "if the cell contains a cell (see C{1,1}
) just unwrap its content in length(C{:,i})
different cells. As instead if the cell contains an array, assign each element of this array to a different cell.".
Now the cell array A
has the form
and I hope this is what you're looking for.
Upvotes: 2