这是什么错误[从Matlab中的文本文件中读取输入]? [英] Whats wrong with this [reading input from a text file in Matlab]?

查看:171
本文介绍了这是什么错误[从Matlab中的文本文件中读取输入]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件(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 

在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] 


我试过这段代码:

pre $ f $ fid = fopen(' C:\\input.txt, 'RB');
data = fread(fid,inf,'float');
data

但是我得到一些垃圾值:

  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

错误在哪里?

解决方案

仅用于读取二进制文件!

相当于文本文件 fscanf ,用法如下:

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

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

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

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




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?

解决方案

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:

这篇关于这是什么错误[从Matlab中的文本文件中读取输入]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆