Filter löschen
Filter löschen

Using fscanf when some elements are not floating point

2 Ansichten (letzte 30 Tage)
jnaumann
jnaumann am 30 Jul. 2013
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

Akzeptierte Antwort

Cedric
Cedric am 30 Jul. 2013
Bearbeitet: Cedric am 30 Jul. 2013
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 Kommentar
Jan
Jan am 30 Jul. 2013
@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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by