Effacer les filtres
Effacer les filtres

How can I use textscan without delimiter?

7 vues (au cours des 30 derniers jours)
Jung-Woo
Jung-Woo le 10 Juin 2015
Commenté : Jung-Woo le 10 Juin 2015
Let's say some numeric data is not delimited, buth we can delimit it based on their location. For example, I would like to read the following data using textscan:
950 99810251026 999 496
951 999102610271000 785
9521000102710281001 497
9531001102810291002 498
10001061108410851062 438
10011062108510861063 439
my code is:
cell2mat(textscan(fid, '%4f%4f%4f%4f%4f%4f'));
and the result is:
950 9981 251 26 999 496
951 9991 261 271 0 785
9521 1 271 281 1 497
9531 11 281 291 2 498
1000 1061 1084 1085 1062 438
1001 1062 1085 1086 1063 439
but what I wanted is:
950 998 1025 1026 999 496
951 999 1026 1027 1000 785
952 1000 1027 1028 1001 497
953 1001 1028 1029 1002 498
1000 1061 1084 1085 1062 438
1001 1062 1085 1086 1063 439
What's wrong with my code?

Réponse acceptée

per isakson
per isakson le 10 Juin 2015
Modifié(e) : per isakson le 10 Juin 2015
Must be done in two steps
  • read as character to avoid the white-space-magic
  • convert to numerical
fid = fopen( 'cssm.txt' );
cac = textscan( fid, '%4c%4c%4c%4c%4c%4c', 'Whitespace', '' );
fclose( fid );
buf = cellfun( @(str) str2num( str ), cac, 'uni', false );
cell2mat( buf )
outputs
ans =
950 998 1025 1026 999 496
951 999 1026 1027 1000 785
952 1000 1027 1028 1001 497
953 1001 1028 1029 1002 498
1000 1061 1084 1085 1062 438
1001 1062 1085 1086 1063 439
The last line of the text file needs to be terminated by a new-line-character(?)
  1 commentaire
Jung-Woo
Jung-Woo le 10 Juin 2015
Thank you so much. It works.

Connectez-vous pour commenter.

Plus de réponses (1)

Walter Roberson
Walter Roberson le 10 Juin 2015
str2double( textscan(fid, repmat('%4c',1,6)) )
The mistake in your code is that the counts for %4f do not start until the first non-blank character of the field. ' 1234567' with '%4f' format skips the blank and counts the 4 from '1' grabbing '1234'.
It is tempting to try to use 'Whitespace', '' so that it doesn't skip blanks. Unfortunately, when reading from a file, the numeric formats fail if they are required to start parsing from a blank instead of starting from a number-forming character (digit, + or -, decimal).
  4 commentaires
Jung-Woo
Jung-Woo le 10 Juin 2015
Thank you. I will try it later.
Jung-Woo
Jung-Woo le 10 Juin 2015
Yes, I confirmed it works. Thanks a lot.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Data Type Conversion dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by