-1

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)

The_Learner
  • 589
  • 1
  • 6
  • 16

2 Answers2

0

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};
amahmud
  • 434
  • 4
  • 14
  • Thank you very much, the code is not working. It is starting at 7th row but, dataArray is giving me a combination of doubles and cells, I am unable to extract two values specifically – The_Learner Jul 24 '18 at 05:36
  • I think there's need to be some modification. Can you upload the data in the question? Just remove the image and put the actual texts from the .txt file. – amahmud Jul 24 '18 at 05:44
  • text file attached, please find – The_Learner Jul 24 '18 at 05:53
0

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.

Paolo
  • 21,270
  • 6
  • 38
  • 69