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.
Corresponding .txt file is attached in the following link (Link)
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.
Corresponding .txt file is attached in the following link (Link)
Hopefully this will work.
delimiter = ' ';
startRow = 7;
fileID = fopen(filename,'r');
formatSpec = '%f%f%[^\n\r]';
dataArray = textscan(fileID, formatSpec,startRow-startRow+1, 'Delimiter', delimiter, 'HeaderLines' ,startRow-1, 'ReturnOnError', false,'MultipleDelimsAsOne',1, 'EndOfLine', '\r\n');
val1 = dataArray{1,1};
val2 = dataArray{1,2};
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.