How to recognise a specific format with textscan?

1 view (last 30 days)
Hi!
I have a text file of some lines with this format:
1-Capital of France-5-Paris-0
2-............-6-soccer
etc
I want to use textscan and take only up to the number of letters the solution has, and then do the same with only the solution. It must work for any field with the format above:
I have tried different things, but I really don't know how to do it.
Thank you.
  1 Comment
dpb
dpb on 7 Dec 2013
What does "...take only up to the number of letters the solution has" mean, precisely. What is a solution in this context?
Also, the sample you posted is shown as a single line...where's the line break actually located? Unfortunately, TMW can't seem to get into their heads that a coding forum shouldn't have linewrap on as a default so you'll have to format the file as code to get it to show up properly. Put a couple of blanks in front of the first line w/ a line break in front of it and then break the lines where supposed to be. Observe in Preview window and keep working until it looks right there.
Just as a guess, it looks like you using
'delimiter','-'
might solve most of your problems altho variable-length character fields can be a pit(proverbial)a...

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 7 Dec 2013
If you want to use textscan to read this, then you will need to request that it read only one item (a size), and then you will need to request that it read the dash followed by the appropriate size, such as in
nchar_c = textscan(fid, '%f-', 1);
str1 = textscan(fid, sprintf('%%%ds', nchar_c{1}), 1);
and keep going like that.
This would be a very inefficient use of textscan(), and it would be much more efficient to use fread() when you know how many characters you are going to read in.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!