Extract data from a .txt file
Show older comments
Hello! The data inside the .txt file has many sets of data separated by the same word. I would like to have so for each set of data one row with 2 columns, which will contain: the reference number after 'ref' and from the 26th row the value from the 4th column. So, for example from the 1st data set : 655158 100.0 I tried something with textscan function but i haven't reached the results.Thank you!
2 Comments
Bob Thompson
on 14 Feb 2018
Edited: Bob Thompson
on 14 Feb 2018
So you want one pair of numbers for each block of data? Or you want to have a set of data which contains the reference number, and then the first column from the block of data?
Ultimately, you might try using a for loop to run through each line, and then use the fgetl() command to draw each line as a value to be evaluated.
for I = 1:end
line = fgetl(openfile)
if line == something
data(I,1) = reference
elseif line == somethingelse
data(I,2) = numbers
end
end
I find that this is usually the best way for me to work through text files with mixed numbers and strings, but I'm sure somebody on here has a better method.
irenne11
on 15 Feb 2018
Answers (2)
Jeff Miller
on 14 Feb 2018
This function loads all of the numbers into one big long list. You can then grab out the numbers you want if you know their sequential positions within the list (e.g., you want the 4th, 8th, 104th, 108th, etc numbers):
function outNums = GetNumsInAsciiFile(sFName)
% Extract the numbers from any ASCII file into a vector, ignoring the text.
% Load the whole file into an array of char:
fid = fopen(sFName, 'r');
c1 = fscanf(fid,'%c');
fclose(fid);
% Split the file into tokens delimited by white space:
Tokens = strsplit(c1);
% Convert the tokens into numbers (returns NaN for any token that is not a number):
outNums = str2double(Tokens);
% Get rid of the NaN's:
outNums(isnan(outNums)) = [];
end
Image Analyst
on 14 Feb 2018
0 votes
That looks like such a variable format that I don't think you can use a built-in function like importdata(), etc. You'll have to write your own custom reader from lower level functions like fgetl(), sscanf(), textscan(), etc. It's too much work for any of us to do for you (it's no 3 minute job!), so good luck.
Categories
Find more on Large Files and Big Data in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!