How do I read in this text file using fopen fclose and fscanf and then split each column into variables?

3 views (last 30 days)
I have linked my text file, I need to use functions suh as fopen, fclose and fscanf to read in the text file. Once read in I then need to figure out how to split each column eg MPG etc into their own variables. I have been stuck on this for over 2 weeks now and cant seem to make any progress.
Thank you for any help

Answers (1)

Star Strider
Star Strider on 2 Dec 2020
If you have R2013b or later, use readtable:
T1 = readtable('car_data.txt', 'VariableNamingRule','preserve');
with:
FirstFiveRows = T1(1:5,:)
producing:
FirstFiveRows =
5×9 table
MPG Cylinders displacement horsepower weight acceleration model year origin car name
___ _________ ____________ __________ ______ ____________ __________ ______ _____________________________
18 8 307 130 3504 12 70 1 {'chevrolet chevelle malibu'}
15 8 350 165 3693 11.5 70 1 {'buick skylark 320' }
18 8 318 150 3436 11 70 1 {'plymouth satellite' }
16 8 304 150 3433 12 70 1 {'amc rebel sst' }
17 8 302 140 3449 10.5 70 1 {'ford torino' }
See Access Data in Tables to understand how to work with them if you are not familiar with them.
.
  2 Comments
Aidan Goy
Aidan Goy on 2 Dec 2020
Thank you for this, I would like to learn how to do it "manually" also by uing fuctions such as fopen, fclose and fscanf, could you suggest some reading that would help me product the same result when using those functions?
thanks
Star Strider
Star Strider on 2 Dec 2020
My pleasure!
Instead of fscanf, an easier solution would be to use textscan. Each column would be read in as a different cell array unless you set CollectOutput to true.
I support your wanting to learn to use the more basic functions, however they are more trouble than they’re worth for reading files. I migrated away from them as soon as better functions were introduced. (I’ve been using MATLAB since 1993, and suffered through getting fscanf to work for severall years. I am more than ecstatic at not having to use it now!)

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!