How to read an ascii text file and extract the data in a matrix?
2 views (last 30 days)
Show older comments
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 Comment
Answers (1)
per isakson
on 27 Jun 2014
Edited: per isakson
on 27 Jun 2014
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 Comments
per isakson
on 27 Jun 2014
Edited: per isakson
on 27 Jun 2014
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.
See Also
Categories
Find more on String in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!