【问题标题】:Specifying Data Type When Reading from File in MATLAB在 MATLAB 中读取文件时指定数据类型
【发布时间】:2013-09-16 17:31:20
【问题描述】:

我正在尝试通过文本文件将实验收集的数据读入 MATLAB。数据都是八列的整数,用空格隔开。

我想打开文件,读入数据,然后reshape成代表数组。

所以,我有:

fileID = fopen('String name of file');
A = fread(fileid);
B = reshape(A, (length(A) / 8), 8);

默认情况下,fread 假定数据是双精度的,但是当我尝试指定整数时,例如 fread(fileid, inf, 'int'),数据仍然会出现错误的值。

数据由 Java 程序输出为“int”,并在 Linux 环境中生成,但现在在 Windows 中(我只有 MATLAB 许可证)。我认为这是为fread 指定正确数据类型的问题,但我不确定。

有什么想法吗?

【问题讨论】:

  • 使用dlmreadcsvimport(免责声明:我的贡献)来读取分隔数据而不是fread
  • 工作正常。谢谢。

标签: java file matlab input types


【解决方案1】:

我不知道如何使用 fread,但 textscan 应该可以工作:

% Open file
fid = fopen('file.txt');

% Scan 8 columns of numeric values
tmp = textscan( fid, repmat('%f ', [1 8]));

% Close file handle
fclose(fid);

% Convert to int and join columns into matrix
data = int32(cat(2, tmp{:}));

【讨论】:

  • 这样就达到了预期的效果,但是Praetorian 对'dlmread' 的建议更直接一些。
【解决方案2】:

使用*int 代替int。可能尝试int32 或其他与平台无关的语法。来自fread的手册:

By default, numeric and character values are returned in class 
'double' arrays. To return these values stored in classes other 
than double, create your PRECISION argument by first specifying 
your source format, then following it by '=>', and finally 
specifying your destination format. If the source and destination 
formats are the same then the following shorthand notation may be 
used:

    *source

which means:

    source=>source

另请注意,您可以使用简化的整形语法:

B = reshape(A, [], 8);

【讨论】:

  • 这不会产生预期的结果。数据太多无法确定,但看起来与仅使用 'int' 的效果相同
  • 嗯,A 应该是具有该语法的 int。尝试A = fread(fileid,'*int32'); 或使用另一种独立于平台的语法,如uint32int16 等。在 fread 后立即设置断点以查看变量类型。谢谢。
猜你喜欢
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-04
  • 2016-03-17
  • 1970-01-01
相关资源
最近更新 更多