MATLAB爱好者论坛-LabFans.com

MATLAB爱好者论坛-LabFans.com (https://www.labfans.com/bbs/index.php)
-   资料存档 (https://www.labfans.com/bbs/forumdisplay.php?f=72)
-   -   这是什么问题[在Matlab中从文本文件读取输入]? (https://www.labfans.com/bbs/showthread.php?t=22783)

poster 2019-12-10 16:49

这是什么问题[在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] 我尝试了这段代码:

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 [B]错误在哪里?[/B]


回答:
[B]fread[/B]仅用于读取二进制文件!
文本文件的等效项是[B][URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/fscanf.html"]fscanf[/URL][/B] ,用法如下:


fid = fopen('c:\\input.txt','rt'); data = fscanf(fid, '%f', inf)'; fclose(fid); 或者在您的情况下,只需使用[B][URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/load.shtml"]load[/URL][/B] :

data = load('c:\\input.txt', '-ascii');
MATLAB中还有许多其他方法可以从文件中读取文本数据:
[LIST][*] [URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/dlmread.html"]dlmread[/URL][*] [URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/textscan.html"]文字扫描[/URL][*] [URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/importdata.html"]导入数据[/URL][/LIST]
[url=https://stackoverflow.com/questions/1457177]更多&回答...[/url]


所有时间均为北京时间。现在的时间是 23:35

Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.