Text File Reading with Text and Numbers

I am trying to extract the only numerical data from the attached data file.
I am using this code:
clc
clear all
fid = fopen('Ex2.txt','r'); %# Open the file
results = textscan(fid,[repmat(' %*s',1,6) ... %# Read 5 strings, ignoring them
'%f %f'], ... %# Read 2 numeric values
'Whitespace','\t\n\r',... %# Add \n and \r as whitespace
'CollectOutput',true); %# Collect numeric values
fclose(fid); %# Close the file
results1 = results{1};
But i am not getting the required data.
Please help.
Thanks

Answers (2)

fid = fopen('Ex2.txt','r'); %# Open the file
result = textscan(fid, [repmat('%*s', 1, 6), '%f%f%f%f'], 'Whitespace',' \t\n\r', 'CollectOutput', 1, 'MultipleDelimsAsOne', 1)
fclose(fid)
results1 = permute(reshape(results{1}.', 2, 2, []),[2 1 3])

5 Comments

Dear Roberson, thanks for your quick reply.
Actually I have file of long data (attached). After each 1001 numerical entries, I got text. How can I extract the numerical data from this file..
My final target is to get the data in column form for each block of 1001 numerical data...
Your long file does not appear to be attached.
Dear Walter Roberson,
This is the file.
Your original file had two sets of headers and two sets of data; the two sets happened to be identical. This file has only one set of headers and one set of data. Is it the general case that you will have multiple headers and data, all of which need to be read in? Or was the first example a mistake and you will only have one set of headers and data?
If you will only have one set of headers and data, then
fid = fopen('Ex.txt','r'); %# Open the file
result = cell2mat( textscan(fid, '%f%f', 'HeaderLines', 2, 'CollectOutput', 1) );
fclose(fid);

Sign in to comment.

f = fopen('Ex.txt');
c = textscan(f,'%s','delimiter','\n');
fclose(f);
z = regexp(c{:},'(\-?\<\d+\.?\d*\>)','tokens');
z = z(cellfun(@(x)~isempty(x) & numel(x)>1,z));
out = str2double(cell2mat(cell2mat(z)));

Categories

Asked:

on 22 Oct 2016

Commented:

on 24 Oct 2016

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!