Can't read formatted data (textread, textscan, others)

조회 수: 5 (최근 30일)
M S
M S 2012년 1월 2일
편집: per isakson 2015년 9월 4일
For the life of me, I can't figure out how to properly use textread, textscan and other similar formatted text functions. I'd like to read a file like this ('test2.txt'):
header1 header2 header3 header4
abc 1 2 3
def 4 5 6
ghi 7 8 9
And build a matrix = [1 2 3; 4 5 6; 7 8 9] and a cell array containing {abc; def; ghi}. From examples posted here and elsewhere, this should work:
fid = fopen('test2.txt');
data = textscan(fid,'%s %f %f %f','delimiter',' ','headerlines',1)
fclose(fid);
But it doesnt. Output:
data =
{1x1 cell} [0x1 double] [0x1 double] [0x1 double]
and the 1x1 cell contains just ''
I've since tried ~ a dozen other examples of this function and similar functions and haven't gotten any to work!
For example: http://www.mathworks.com/matlabcentral/answers/21810-reading-a-text-file - Using Jan's code and the OP's data which is formatted similarly to mine, I get the same problem as above: a bunch of empty cells/vectors.
Another recent post: http://www.mathworks.com/matlabcentral/answers/24995-simple-file-i-o-problem-help-needed - Same deal. Friedrich's solution doesn't give me the same output as he shows.
Finally, I copied/pasted the example in 'help textscan'. Same problem, except the first cell does contain some gibberish 'ÿþS'. What am I missing here? Thanks for your time.
SOLUTION. (In comments section in Walter Roberson's Answer) Notepad defaulted to saving files as Unicode format. When saving a text file in notepad, changing the "Encoding" option (near bottom of save as dialog window) from Unicode to either ANSI or UTF-8 resulted in proper code execution. Thank you!

채택된 답변

Walter Roberson
Walter Roberson 2012년 1월 2일
gibberish 'ÿþ' tells us that your file is encoded by UTF-16 Little Endian.
Please try with
fopen('test2.txt', 'rt')
so that your file is treated as a text file rather than as a binary file.
  댓글 수: 10
Walter Roberson
Walter Roberson 2012년 1월 3일
"plain text" is ASCII or ISO-8896-1
Walter Roberson
Walter Roberson 2012년 1월 3일
편집: per isakson 2015년 9월 4일
Which MATLAB version are you using? I found a thread indicating a textscan issue in some earlier versions and showing a work-around: http://www.mathworks.com/matlabcentral/answers/16493-textscan-or-import-of-unicode-encoded-textfile

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by