Using fscanf when some elements are not floating point

2 次查看(过去 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 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by