Import text file with blank lines. Matlab not replacing them with NaN

4 ビュー (過去 30 日間)
mashtine
mashtine 2015 年 1 月 29 日
編集済み: per isakson 2015 年 1 月 30 日
Matlab is not replacing my blank lines in my txt file with NaN but just joins all the data together. Unfortunately I need to data in the exact order it is as each line is a unique timestamp but the times are do not come in the txt file.
Any ideas? Tried importdata and textscan with no luck. Using R2014b

採用された回答

per isakson
per isakson 2015 年 1 月 29 日
編集済み: per isakson 2015 年 1 月 30 日
Remains (at least) two possibilities
  • a loop over fgetl
  • read the file as one string, replace empty lines by 'nan nan ... ' and parse with textscan
Example (R2013a)
>> cac = cssm;
>> cac{:}
ans =
16 2 3 13
5 11 10 8
NaN NaN NaN NaN
9 7 6 12
4 14 15 1
where
function cac = cssm
str = fileread('cssm.txt');
str = regexprep( str, '(?<=\r?\n)[ ]*(?=\r?\n)', 'nan nan nan nan');
cac = textscan( str, '%f%f%f%f', 'CollectOutput', true );
end
and where cssm.txt contains
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
&nbsp
Replace
str = regexprep( str, '(?<=\r?\n)[ ]*(?=\r?\n)', 'nan nan nan nan');
by
str = regexprep( str, '(?<=\r?\n)[ ]*(?=\r?\n)' ...
, 'nan nan nan nan', 'emptymatch' );
to handle empty lines
  10 件のコメント
mashtine
mashtine 2015 年 1 月 30 日
Thanks a lot guys!!
per isakson
per isakson 2015 年 1 月 30 日
Hi Cedric,
You are right, "\r" is not needed in the "look behind". And possibly, it saves on execution time to exclude it.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by