Search code examples
matlabtextscan

Reading formatted text from a file


I'm tring to read the follwing text file with Matlab:

00000008.jpg 1 2 1
00000001.jpg 1 2 1
00000054.jpg 1 2 1

What I want to extract is each column of each line in order to access it.

I've tried the following code:

fileLabels = fopen('file.txt');
C = textscan(fileLabels,'%s %n %n %n');
celldisp(C)

And it returns:

C{1}{1} =
00000008.jpg

C{1}{2} = 
00000001.jpg

C{1}{3} =
00000054.jpg

Which is good, because this way I have the first string separated in cells, but, when I try to get the numbers, they appear this way:

C{2} =
     1
     1
     1

C{3} =
     2
     2
     2

C{4} =
     1
     1
     1

Instead of having them separated in cells, they appear all in one cell. If I try to access to one cell of the 2º column, it appears the following error:

>> C{2}{1}
Cell contents reference from a non-cell array object.

Please, anyone knows how to extract each column separately line by line?


Solution

  • The numbers are in an array rather than cell, which should be more convenient for later process. You can access the numbers by

    C{2}(1) % C{2} is 3x1 array, not cell
    

    If this does not fit your need, you may try some function like importdata.