这有什么问题[从Matlab中的文本文件中读取输入]?

Laz*_*zer 1 formatting file-io matlab input

我有一个文本文件(c:\ input.txt),它有:

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
Run Code Online (Sandbox Code Playgroud)

在Matlab中,我想把它读作:

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]
Run Code Online (Sandbox Code Playgroud)

我试过这段代码:

fid=fopen('c:\\input.txt','rb');
data = fread(fid, inf, 'float');
data
Run Code Online (Sandbox Code Playgroud)

但我得到一些垃圾值:

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
Run Code Online (Sandbox Code Playgroud)

哪里出错了?

Amr*_*mro 8

fread仅用于读取二进制文件!
文本文件的等价物是fscanf,用法如下:

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

或者在您的情况下,只需使用load:

data = load('c:\\input.txt', '-ascii');
Run Code Online (Sandbox Code Playgroud)


MATLAB中有许多其他方法可以从文件中读取文本数据: