我将在matlab中读取一个大的csv文件,其中包含以下行:
1, 0, 1, 0, 1
1, 0, 1, 0, 1, 0, 1, 0, 1
1, 0, 1
1, 0, 1
1, 0, 1, 0, 1
0, 1, 0, 1, 0, 1, 0, 1, 0
要读取大文件,我使用的是textscan
,但是我应该在文本文件的每一行中定义一些期望的参数。
使用csvread
会有所帮助,但是它太慢并且似乎效率不高。
是否有任何方法可以将textscan
用于每一行中未知数量的输入?还是您对此情况有其他建议?
答案 0 :(得分:2)
由于您说“ 用零填充的数字矩阵会很好”,因此有一种使用textscan
的解决方案可以为您提供解决方案。但是要注意的是,您必须知道一行可以包含的最大元素数(即文件中最长的一行)。
只要您知道,'EndOfLine','\r\n'
的其他参数组合就可以使您读取不完整的行:
如果设置参数differentRows.txt
,则文档说明:
如果缺少值并且在行尾有行尾序列 文件的最后一行,然后textscan为那些返回空值 领域。这样可以确保输出单元阵列C中的各个单元 都是一样的大小。
因此,将问题中的示例数据另存为% be sure about this, better to overestimate than underestimate
maxNumberOfElementPerLine = 10 ;
% build a reading format which can accomodate the longest line
readFormat = repmat('%f',1,maxNumberOfElementPerLine) ;
fidcsv = fopen('differentRows.txt','r') ;
M = textscan( fidcsv , readFormat , Inf ,...
'delimiter',',',...
'EndOfLine','\r\n',...
'CollectOutput',true) ;
fclose(fidcsv) ;
M = cell2mat(M) ; % convert to numerical matrix
,下面的代码:
>> M
M =
1 0 1 0 1 NaN NaN NaN NaN NaN
1 0 1 0 1 0 1 0 1 NaN
1 0 1 NaN NaN NaN NaN NaN NaN NaN
1 0 1 NaN NaN NaN NaN NaN NaN NaN
1 0 1 0 1 NaN NaN NaN NaN NaN
0 1 0 1 0 1 0 1 0 NaN
将返回:
NaN
作为替代方案,如果可以显着提高速度,则可以将数据导入整数而不是double。麻烦的是0
没有为整数定义,因此您有2个选择:
% build a reading format which can accomodate the longest line
readFormat = repmat('%d',1,maxNumberOfElementPerLine) ;
只需将定义格式说明符的行替换为:
>> M
M =
1 0 1 0 1 0 0 0 0 0
1 0 1 0 1 0 1 0 1 0
1 0 1 0 0 0 0 0 0 0
1 0 1 0 0 0 0 0 0 0
1 0 1 0 1 0 0 0 0 0
0 1 0 1 0 1 0 1 0 0
这将返回:
99
EmptyValue
)替换 empty 条目定义一个您肯定不会在原始数据中拥有的值(用于快速识别空单元格),然后使用textscan
函数的readFormat = repmat('%d',1,maxNumberOfElementPerLine) ;
DefaultEmptyValue = 99 ; % placeholder for "empty values"
fidcsv = fopen('differentRows.txt','r') ;
M = textscan( fidcsv , readFormat , Inf ,...
'delimiter',',',...
'EndOfLine','\r\n',...
'CollectOutput',true,...
'EmptyValue',DefaultEmptyValue) ;
参数:
>> M
M =
1 0 1 0 1 99 99 99 99 99
1 0 1 0 1 0 1 0 1 99
1 0 1 99 99 99 99 99 99 99
1 0 1 99 99 99 99 99 99 99
1 0 1 0 1 99 99 99 99 99
0 1 0 1 0 1 0 1 0 99
将产生:
options.Cookie.Domain = "localhost";