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

采纳的回答

Cam Salzberger
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
Walter Roberson 2017-9-20
readtable() delegates to textscan() which does not need spaces between the % format elements.
Jeppe Sørensen
Jeppe Sørensen 2017-9-21
By converting NaN to zeros after importing, this works excellently for me. Thank you!

请先登录,再进行评论。

更多回答(1 个)

Cedric
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 个评论
Jeppe Sørensen
Jeppe Sørensen 2017-9-21
This works as intended as well, and is a very good answer. Thank you for this. Cam Salzburgs answer gets accepted, however, as it is a bit simpler.
Cedric
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 CenterFile Exchange 中查找有关 Standard File Formats 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by