필터 지우기
필터 지우기

How to import data from a non-symmetric .txt file.

조회 수: 3 (최근 30일)
Jeppe Sørensen
Jeppe Sørensen 2017년 9월 19일
편집: Cedric 2017년 9월 21일
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