fscanf with text file

12 views (last 30 days)
John
John on 30 Nov 2022
Commented: John on 30 Nov 2022
I have a text file as such:
Jane 43452 68 24 92
Paul 13454 10 34 81.3
Richard 36343 79.5 31 85
Ben 67355 93 11.5 82
Amber 77803 75 93 22
How do I use an fscanf function to seperate the columns into vectors?

Accepted Answer

Walter Roberson
Walter Roberson on 30 Nov 2022
We recommend readtable() for this purpose.
If you use fscanf() then you have the problem that when you mix %s format (for the text) with numeric format, then the characters are emitted as numbers, and there is no boundary emitted so you cannot reliably tell where the characters end and the numbers begin. In order to handle the above situation with fscanf() you would need one of the following approaches:
  1. loop asking to fscanf() with format '%s' and size 1, and take char() of the result to get the first column, then fscanf format '%f%f%f%f' and size [1 4] to read the numeric columns, then back to the beginning of the loop; OR
  2. fscanf with format %*s%f%f%f%f and no size, to read all of the numeric data, after which you would frewind() to return to the beginning of the file and proceed to use a different fscanf to read the text
These kinds of problems go away if you use readtable() or textscan()

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!