Whats wrong with this [reading input from a text f

2019-01-29 02:29发布

问题:

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?

回答1:

fread is for reading binary files only!
The equivalent for text files is fscanf, used as follows:

fid = fopen('c:\\input.txt','rt');
data = fscanf(fid, '%f', inf)';
fclose(fid);

Or in your case, simply use load:

data = load('c:\\input.txt', '-ascii');


There are many other ways in MATLAB to read text data from files:

  • dlmread
  • textscan
  • importdata


回答2:

Your file is a text file, so you should open it for text read:

fid=fopen('c:\\input.txt','rt');

Then, for reading, I find TEXTSCAN to be more powerful than FREAD/FSCANF (the differences between them all are summarized here

data = textscan(f, '%f')

returns a cell array. You can get at the contents with

>> data{1}

ans =

       2
       4
       8
      16
      32
      64
     128
     256
     512
    1024
    2048
    4096
    8192

TEXTREAD is easier to use than TEXTSCAN, but according to the documentation is now outdated.