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
2016년 10월 22일
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
2016년 10월 22일
Jawad Yousaf
2016년 10월 22일
Walter Roberson
2016년 10월 22일
Your long file does not appear to be attached.
Jawad Yousaf
2016년 10월 24일
Walter Roberson
2016년 10월 24일
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
2016년 10월 24일
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에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!