poster
2019-12-10, 16:49
我有一个文本文件(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 错误在哪里?
回答:
fread仅用于读取二进制文件!
文本文件的等效项是fscanf (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/fscanf.html) ,用法如下:
fid = fopen('c:\\input.txt','rt'); data = fscanf(fid, '%f', inf)'; fclose(fid); 或者在您的情况下,只需使用load (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/load.shtml) :
data = load('c:\\input.txt', '-ascii');
MATLAB中还有许多其他方法可以从文件中读取文本数据:
dlmread (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/dlmread.html)
文字扫描 (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/textscan.html)
导入数据 (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/importdata.html)
更多&回答... (https://stackoverflow.com/questions/1457177)
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 错误在哪里?
回答:
fread仅用于读取二进制文件!
文本文件的等效项是fscanf (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/fscanf.html) ,用法如下:
fid = fopen('c:\\input.txt','rt'); data = fscanf(fid, '%f', inf)'; fclose(fid); 或者在您的情况下,只需使用load (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/load.shtml) :
data = load('c:\\input.txt', '-ascii');
MATLAB中还有许多其他方法可以从文件中读取文本数据:
dlmread (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/dlmread.html)
文字扫描 (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/textscan.html)
导入数据 (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/importdata.html)
更多&回答... (https://stackoverflow.com/questions/1457177)