Search code examples
matlabtextscan

MATLAB READING FILE


i am having trouble reading the file, basically, i want to somehow get rid of the unnecessary text and just print out a matrix involving only the numbers.

1 1 -1 1 1 -1 -1 1 1 1 -1 1

1 -1 1 -1 -1 1 1 1 1 -1 1 1

sgfgdf

1 1 1 -1 1 -1 1 -1 -1 -1 -1 1

rtydsfdsfds

1 -1 1 -1 -1 -1 1 1 -1 -1 -1 1

1 1 -1 1 1 -1 -1 -1 1 -1 1 -1

1 -1 1 1 1 1 1 -1 -1 -1 1 -1

what i've tried so far is:

d = fopen('transmission_data.txt')

R = textscan(d, '%f %f', 'headerLines', 3:5)

fclose(d)

but this doesnt work, as i have to put only one number for the textscan, for example, '3', this would get rid of the first 3 lines, but i want to specifically get rid of the third and fifth. maybe there's some other way to read data? Help would be appreciated :)

*note that there is an empty line between the first line of text and the second row of numbers


Solution

  • Read the file by fileread, split it it by regexp and ask textscan to find all the numbers:

    C = regexp(fileread('transmission_data.txt'), '(\n|\r)*', 'split');
    C = C(~cellfun('isempty', C));
    D = cellfun(@(c) textscan(c, '%f'), C);
    R = [D{:}].';
    

    The important point here is that when textscan encounters a row that doesn't contain numbers it returns an empty matrix so when you concatenate the resulting vectors you just get the ones that come from non-string rows. For your example this code returns

    >> R
    R =
         1     1    -1     1     1    -1    -1     1     1     1    -1     1
         1    -1     1    -1    -1     1     1     1     1    -1     1     1
         1     1     1    -1     1    -1     1    -1    -1    -1    -1     1
         1    -1     1    -1    -1    -1     1     1    -1    -1    -1     1
         1     1    -1     1     1    -1    -1    -1     1    -1     1    -1
         1    -1     1     1     1     1     1    -1    -1    -1     1    -1