I have a text file (c:\input.txt) which has:
2.0 4.0 8.0 16.0 32.0 64.0 128.0 256.0 512.0 1024.0 2048.0 4096.0 8192.0
In Matlab, I want to read it as:
data = [2.0 4.0 8.0 16.0 32.0 64.0 128.0 256.0 512.0 1024.0 2048.0 4096.0 8192.0]
I tried this code:
fid=fopen('c:\\input.txt','rb');
data = fread(fid, inf, 'float');
data
but I am getting some garbage values:
data =
1.0e-004 *
0.0000
0.0015
0.0000
0.0000
0.0000
0.0000
0.0000
0.0001
0.0239
0.0000
0.0000
0.0000
0.0000
0.0066
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0000
0.0016
0.0000
0.0000
0.0276
0.0000
0.3819
0.0000
0.0000
Where is the mistake?
Your file is a text file, so you should open it for text read:
Then, for reading, I find TEXTSCAN to be more powerful than FREAD/FSCANF (the differences between them all are summarized here
returns a cell array. You can get at the contents with
TEXTREAD is easier to use than TEXTSCAN, but according to the documentation is now outdated.
fread is for reading binary files only!
The equivalent for text files is fscanf, used as follows:
Or in your case, simply use load:
There are many other ways in MATLAB to read text data from files: