Search code examples
matlabtextscan

Extract or import two Specific values form Text file - MATLAB


I am working on a problem in MATLAB, in which I need to import two specific values (highlighted) from a text file as shown in the figure 1.

figure 1

Corresponding .txt file is attached in the following link (Link)


Solution

  • When you want to extract specific values from a text file you should always consider using regular expressions.

    For getting the two values you highlighted you can use:

    raw = fileread('M7_soil_FN_1.txt');
    val = regexp(raw,'(\d+)\s+(\d+\.\d+)\s+(?=NPTS)','tokens')
    

    The regular expression says:

    • (\d+) Match digits and capture.
    • \s+ Match whitespace.
    • (\d+\.\d+) Match and capture digits, a full stop, more digits.
    • \s+ Match whitespace.
    • (?=NPTS) Positive lookahead to ensure that what follows is NPTS.

    Then convert val to double:

    val = str2double(val{:})
    >>val(1)
    
        5991
    
    >>val(2)
    
        0.0050
    

    If you are interested, you can see the regular expression in action live here.