Using fscanf when some elements are not floating point

조회 수: 3 (최근 30일)
jnaumann
jnaumann 2013년 7월 30일
Hi there
I am trying to use fscanf to read a measurement text file. The file is a matrix of (480x640) floating point numbers. Normally this would be fine however some elements are strings (in this case 'Bad') - is there a way of reading the file in the same way but replacing 'Bad' with NaN, or a better way of doing this?
Currently I have used the following, which reads to the point of the first 'Bad'.
B=fscanf(fid,'%f ',[480 640])
Many thanks in advance
Jack

채택된 답변

Cedric
Cedric 2013년 7월 30일
편집: Cedric 2013년 7월 30일
One way to do it is to start with string replacement.. to illustrate, say that the data file contains
4 5 6 7 8 9
1 2 Bad 4 5 6
Bad 7 8 9 10 11
0 Bad Bad Bad 4 5
then:
>> buffer = fileread('myData.txt') ;
>> buffer = strrep(buffer, 'Bad', 'NaN') ; % or regexprep().
>> sscanf(buffer, '%f', [6 4]).'
ans =
4 5 6 7 8 9
1 2 NaN 4 5 6
NaN 7 8 9 10 11
0 NaN NaN NaN 4 5
  댓글 수: 1
Jan
Jan 2013년 7월 30일
@jnaumann: Just to repeat the obvious solution: Replace the not recognized "Bad" by the recognized "NaN" in the file. Then the reading is straight forward. Sometimes simplicity is really nice. +1

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Low-Level File I/O에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by