Search code examples
matlabtextscan

How can i read text file and load data to an array?


I have a .txt file that follows the next format:

00:00.300      ID:4        zzzzzzzzzzz                
00:02.155      ID:4        aaaaaaaaaaaaa        
00:04.662      ID:4        dsadasd  
**00:32.283**      ID:4        level **790**  
00:32.155      ID:4        Sfghgfs  
00:32.200      ID:4        Tsdfsdfdfsff  
**00:32.205**      ID:4        level **640**  
00:32.206      ID:4        Sadssd  
00:32.208      ID:4        asdasgsfgsgsagsa  
00:32.210      ID:4        adasgx  
00:32.212      ID:4        Masddasdas.  
**01:40:40.698**   ID:4        level **500**

So, I want to scan the file and extract the time to an array whenever appears in the line "level XXX". After this, i want to read the correspondent level and save in another array to draw a graphic with both.

I tried the functions: textscan and strfind but it doesn't work. Can you guys help me?


Solution

  • You can use a regular expression:

    raw = fileread('mytext.txt');
    tokens = regexp(raw,'((?:\d{2}:)?\d{2}:\d{2}\.\d{3})[^\n]+level[^\d]+(\d{3})','tokens');
    tokens = [tokens{:}];
    timestamps = tokens(1:2:end);
    levels = tokens(2:2:end);
    

    Inspect outputs:

    >> timestamps
    
    timestamps =
    
      1×3 cell array
    
        {'00:32.283'}    {'00:32.205'}    {'01:40:40.698'}
    
    >> levels
    
    levels =
    
      1×3 cell array
    
        {'790'}    {'640'}    {'500'}
    

    You can see how the regex works here.