How can I import a file that contains text and numerical values?

조회 수: 4 (최근 30일)
Ryan
Ryan 2013년 8월 6일
Hi Everyone,
I need your help. I'm writing a program that must pull data from a very large file that is formatted like this:
  • 1 1 10230435 3 red no no 1 5 yes
  • 3 4 23423423 4 blue no yes 2 3 no
  • 4 2 23433554 5 red no no 4 2 yes
  • 2 5 23434234 7 green no yes 4 5 no
This is just a sample. The real data actually has 15 columns and has thousands of rows. I have tried the following ways to read the data.
if true
% s = load('Mfile.m')
% fid = fopen('Mfile.m','r')
% s = fscanf(fid,'%s')
% fid = fopen('Mfile.m','r')
% s = fscanf(fid,'%f')
% s = xlsread('Mfile.xls')
end
The load and fscanf commands give me errors. The xlsread assigns all of the text NaN values. I'm running out of ideas, so any help is greatly appreciated.
Thanks!
  댓글 수: 1
Ryan
Ryan 2013년 8월 6일
Also I have tried textscan like this,
  • fid = fopen('Mfile.m','r')
  • a = textscan(fid,'%d %d %d %d %s %s %s %d %d %s')
But I receive a matrix with no values.

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

채택된 답변

dpb
dpb 2013년 8월 6일
Lose the blanks in the format string--that's causing grief in trying to match them in the parsing...
>> fid=fopen('ryan.txt','r');
>> a=textscan(fid,'%d%d%d%d%s%s%s%d%d%s')
a =
Columns 1 through 7
[4x1 int32] [4x1 int32] [4x1 int32] [4x1 int32] {4x1 cell} {4x1 cell} {4x1 cell}
Columns 8 through 10
[4x1 int32] [4x1 int32] {4x1 cell}
>> a{1}
ans =
1
3
4
2
>> frewind(fid)
>> b=textscan(fid,'%d%d%d%d%s%s%s%d%d%s','collectoutput',1)
b =
[4x4 int32] {4x3 cell} [4x2 int32] {4x1 cell}
>> b{1}
ans =
1 1 10230435 3
3 4 23423423 4
4 2 23433554 5
2 5 23434234 7
>> fid=fclose(fid);
BTW, why on earth would you name a text file with an ".m" extension???
  댓글 수: 1
Ryan
Ryan 2013년 8월 6일
Thanks! And I couldn't tell you honestly. I switched it to .txt

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

추가 답변 (1개)

Azzi Abdelmalek
Azzi Abdelmalek 2013년 8월 6일
fid=fopen('fic.txt')
out=textscan(fid,'%f %f %f %f %s %s %s %f %f %s')
fclose(fid)

카테고리

Help CenterFile Exchange에서 Number Theory에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by