在MATLAB中使用textscan读取固定宽度字符串时出错

时间:2013-06-19 09:09:28

标签: string matlab textscan

我正在使用textscan从文本文件中读取固定宽度(9个字符)的数据。 Textscan在包含字符串的某一行失败:

'   9574865.0E+10  '

我想从中读到两个数字:

957486 5.0E+10

问题可以这样复制:

dat = textscan('   9574865.0E+10  ','%9f %9f','Delimiter','','CollectOutput',true,'ReturnOnError',false);

返回以下错误:

Error using textscan
Mismatch between file and format string.
Trouble reading floating point number from file (row 1u, field 2u) ==> E+10

令人惊讶的是,如果我们添加一个减号,我们不会收到错误,但错误的结果是:

dat = textscan('  -9574865.0E+10  ','%9f %9f','Delimiter','','CollectOutput',true,'ReturnOnError',false);

现在dat {1}是:

    -9574865           0

显然,我需要两种情况才能工作。我目前的解决方法是在字段之间添加逗号并使用逗号作为文本扫描中的分隔符,但这很慢并且不是一个好的解决方案。有没有什么办法可以使用textscan或其他内置函数(出于性能原因)正确读取这个字符串MATLAB函数?

1 个答案:

答案 0 :(得分:0)

我怀疑textscan 首先修剪前导空格,然后解析格式字符串。我想这个,因为如果你从

改变你的格式字符串
'%9f%9f'

'%6f%9f'

你的单行突然工作。另外,如果你试试

'%9s%9s'

你会看到第一个字符串删除了前导空格(因此有3个字符“太多”),但由于某种原因,最后一个字符串会保留其尾随空格。

显然,这意味着您必须确切地知道两个数字中有多少位数。我猜这不可取。

解决方法可能如下所示:

% Split string on the "dot"
dat = textscan(<your data>,'%9s%9s',...
    'Delimiter'     , '.',...
    'CollectOutput' , true,...
    'ReturnOnError' , false);

% Correct the strings; move the last digit of the first string to the 
% front of the second string, and put the dot back
dat = cellfun(@(x,y) str2double({y(1:end-1),  [y(end) '.' x]}),  dat{1}(:,2), dat{1}(:,1), 'UniformOutput', false);

% Cast to regular array
dat  = cat(1, dat{:})
相关问题