How to import data from a non-symmetric .txt file.
3 次查看(过去 30 天)
显示 更早的评论
We have the following data file:
1
2 3
5 6 7
How can I import that into MATLAB easily, so the empty block become zero? Like this:
1 0 0
2 3 0
4 5 6
load does not work and importdata gives:
1 NaN
2 3
4 5
6 NaN
0 个评论
采纳的回答
Cam Salzberger
2017-9-19
Hello Jeppe,
If you give an explicit format to use, the data read functions will try to stick to it as best as possible. My personal preferred data read function is readtable. Just tell it not to assume there are header lines (which is probably why it's skipping the "1" by default), and read using your desired format:
t = readtable('datafile.txt','ReadVariableNames',false,'HeaderLines',0,'Format','%f %f %f');
-Cam
5 个评论
Walter Roberson
2017-9-20
readtable() delegates to textscan() which does not need spaces between the % format elements.
更多回答(1 个)
Cedric
2017-9-20
编辑:Cedric
2017-9-20
If you are stuck with usual tools, try this:
content = fileread( 'virusDat.txt' ) ;
% - Split in rows, remove extra empty ones.
data = strsplit( content, '\n' ) ;
while isempty( data{end} )
data(end) = [] ;
end
% - Convert to numeric and get max number of columns.
data = cellfun( @(x) sscanf( x, '%d' ), data, 'UniformOutput', false ) ;
nCols = max( cellfun( @numel, data )) ;
% - Define padding function and pad with e.g. NaNs.
pad_fun = @(x) [reshape( x, 1, [] ), repelem( NaN, 1, nCols-numel( x ))] ;
data = cellfun( pad_fun, data, 'UniformOutput', false ) ;
% - Concatenate padded rows.
data = vertcat( data{:} ) ;
EDIT : replaced
nCols = numel( data{end} ) ;
with
nCols = max( cellfun( @numel, data )) ;
in case you don't always have this pyramidal structure.
2 个评论
Cedric
2017-9-21
编辑:Cedric
2017-9-21
My pleasure! It was just to give you an alternate approach for dealing with "unorthodox" files. Note that it doesn't require that you hard-code 24 for defining a format string and that it is faster than READTABLE, essentially because of the detection of options in READTABLE for importing that takes time.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Standard File Formats 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!