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

Respuestas (2)

Walter Roberson
Walter Roberson el 22 de Oct. de 2016
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 comentarios

Jawad Yousaf
Jawad Yousaf el 22 de Oct. de 2016
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..
Jawad Yousaf
Jawad Yousaf el 22 de Oct. de 2016
My final target is to get the data in column form for each block of 1001 numerical data...
Walter Roberson
Walter Roberson el 22 de Oct. de 2016
Your long file does not appear to be attached.
Jawad Yousaf
Jawad Yousaf el 24 de Oct. de 2016
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);

Iniciar sesión para comentar.

Andrei Bobrov
Andrei Bobrov el 24 de Oct. de 2016
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)));

Categorías

Más información sobre Characters and Strings en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 22 de Oct. de 2016

Comentada:

el 24 de Oct. de 2016

Community Treasure Hunt

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

Start Hunting!

Translated by