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

답변 (2개)

Walter Roberson
Walter Roberson 2016년 10월 22일

0 개 추천

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

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

댓글을 달려면 로그인하십시오.

Andrei Bobrov
Andrei Bobrov 2016년 10월 24일

0 개 추천

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)));

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

질문:

2016년 10월 22일

댓글:

2016년 10월 24일

Community Treasure Hunt

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

Start Hunting!

Translated by