how to read a text file line by line and store in an array

2 views (last 30 days)
My text file is like this:-
3
2
3
-1
2
3.5
I'm doing it like this :-
fileID=fopen('sample.txt','r');
formatSpec='%d';
A=[ ];
A=fscanf(fileID,formatSpec,sizeA)
disp(A)
I am assuming array A is created and it is reading byte by byte into A for some reason nothing is printing. Also i need help because it would stop reading at -1 becausr it is a negative value. How can i read different data types ? i want to store them into a array after reading from a file.

Accepted Answer

Mehmed Saad
Mehmed Saad on 18 Apr 2020
Edited: Mehmed Saad on 18 Apr 2020
Change formatSpec from %d to %f
fileID=fopen('sample.txt','r');
formatSpec='%f';
A=fscanf(fileID,formatSpec)
A =
3.0000
2.0000
3.0000
-1.0000
2.0000
3.5000
Use %c to read (either it is number or string)
fileID=fopen('sample.txt','r');
formatSpec='%c';
A=fscanf(fileID,formatSpec)
A =
'3
2
3
-1
2
3.5'

More Answers (0)

Categories

Find more on Cell Arrays 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!