Using fscanf when some elements are not floating point
6 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponse acceptée
Cedric
le 30 Juil 2013
Modifié(e) : Cedric
le 30 Juil 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 commentaire
Jan
le 30 Juil 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
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Low-Level File I/O dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!