How to read an ascii text file and extract the data in a matrix?
조회 수: 5 (최근 30일)
이전 댓글 표시
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
답변 (1개)
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
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 Center 및 File Exchange에서 Text Files에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!