How to read an ascii text file and extract the data in a matrix?

조회 수: 5 (최근 30일)
Baban
Baban 2014년 6월 27일
편집: per isakson 2014년 6월 27일
I have a ascii text file (B1N.SA) with 250 blocks of data which each block have 25 header line and then the data (as you can see below). I don't need the first 25 character and the last 5 character ( *). Could you please help me? I need just in each block to have such as a matrix 299*299.

답변 (1개)

per isakson
per isakson 2014년 6월 27일
편집: per isakson 2014년 6월 27일
Try
out = read_blocks_of_numerical_data( 'B1N.SA', 1000, ',' );
where
function out = read_blocks_of_numerical_data( filespec, block_size, delimiter )
narginchk( 2, 3 )
buffer = fileread( filespec );
if nargin == 2
del_xpr = '[ ]+';
trl_xpr = '[ ]*';
else
del_xpr = ['([ ]*',delimiter,'[ ]*)'];
trl_xpr = ['([ ]*',delimiter,'?[ ]*)'];
end
num_xpr = '([+-]?(\d+(\.\d*)?)|(\.\d+))';
sen_xpr = '([EeDd](\+|-)\d{1,3})?'; % optional scientific E notation
num_xpr = [ num_xpr, sen_xpr ];
nl_xpr = '((\r\n)|\n)';
row_xpr = cat(2,'(^|',nl_xpr,')[ ]*(', num_xpr, del_xpr, ')*' ...
, num_xpr, trl_xpr, '(?=',nl_xpr,'|$)' );
blk_xpr = ['(',row_xpr,')+'];
blocks = regexp( buffer, blk_xpr, 'match' );
is_long = cellfun( @(str) length(str)>=block_size, blocks );
blocks(not(is_long)) = [];
out = cell( 1, length( blocks ) );
for jj = 1 : length( blocks )
out{jj} = str2num( blocks{jj} );
end
end
  댓글 수: 2
Baban
Baban 2014년 6월 27일
Thanks for your reply It's gave just an cell 1*0. and why for block size 1000??
per isakson
per isakson 2014년 6월 27일
편집: per isakson 2014년 6월 27일
block_size is a lower limit of the number of characters in a block of numerical data. I just made a guess.
Why don't you attach a sample file? It's difficult to help without knowing more about the file.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by