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

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

问题描述

我有一个文本文件 (c:input.txt),其中包含:

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

在 Matlab 中,我想把它读作:

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]

我试过这段代码:

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

哪里出错了?

推荐答案

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

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);

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

Or in your case, simply use load:

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


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


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

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

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