How do I read in this text file using fopen fclose and fscanf and then split each column into variables?
10 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(1 个)
Star Strider
2020-12-2
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' }
.
2 个评论
Star Strider
2020-12-2
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!)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!