Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Loading Text File with Multiple sections of headers

Asked by Brendan on 8 Jun 2012

Hi All, I am trying to using the "importdata" command to import to Matlab 2012a from a file that has multiple sections of headers. The file looks like:

header header header

1 1 1

1 1 1

header header header

2 2 2

2 2 2

However, import data will only return the data after the first line of headers (in this example a 2x3 matrix of 1's). How can I get it to also read the data after the second set of headers (so a 4x3 matrix for this example of 1's then 2's). Thank you for the help.

Brendan

2 Comments

Walter Roberson on 8 Jun 2012

Do you know the exact amount of data in each section ahead of time?

Do you want the data broken up into parts, or do you want all the data together?

Does the header always start with the same string?

Brendan on 8 Jun 2012

If the data is all in one matrix in matlab that is fine. The headers are four lines but the directly above the data is always the same. And I know the amount of data in each section ahead of time.

Brendan

Products

No products are associated with this question.

2 Answers

Answer by Walter Roberson on 8 Jun 2012
Accepted answer

As you know the amount of data in each section, fopen() the file, and textscan() it section by section, using the 'HeaderLines' option and passing in the count of the number of lines to read.

numlines = 2;
thissectionCell = textscan(fid, '%f%f%f', numlines, 'HeaderLines', 4, 'CollectOutput', 1);

1 Comment

Brendan on 8 Jun 2012

thank you very much. This worked well. I had to call fopen twice to skip over the second group of headers but it got the job done.

Walter Roberson
Answer by per isakson on 8 Jun 2012

importdata cannot handle your file.

An approach is to

  1. read the file as characters to a string, buf
  2. split the string, buf, into one string of characters per block of header&data
  3. parse each block with textscan

Something like

    function    M = Answer( )    
        fid = fopen( 'cssm.txt', 'r' );
        buf = fread( fid, '*char' );
        sts = fclose( fid );
        while buf > 0 
            ix2 = first position of next header
            str = buf( 1 : ix2-1 ); 
            buf( 1 : ix2-1 ) = [];
            cac  = textscan( str, format );
            peel off the braces   
        end
    end

or write the blocks to separate files and read with importdata.

0 Comments

per isakson

Contact us