How can I read data from the middle of text file?

If I want to read the data in the following txt file, from S(but not include) to the last 056 and store it into an array, what shall I do?
【FROM 192.168.7.2:658161】 058 032 055 003 056 S 058 032 055 003 056 058 032 055 003 056 058 032 055 003 056 058 032 055 003 056 058 032 055 003 056 058 032 055 003 056 058 032 055 003 056 【FROM 192.168.7.2:658161】
I have tried fscanf(Fid,'%d'). It seems that an empty array is returned, because there are characters in the file.
I have also tried the following one, but it does not work as well. Thank you for giving me a help!
while(1)
YY=fopen('exp.txt');
flag=fscanf(YY,'%s');
if ~isempty(findstr(flag, 'S')),
data=fscanf(YY,'%d');
data=data';
j=size(data);
data_index=[1:j(2)];
figure(1);
plot(data_index,data);
fclose(YY);
end
end

2 comentarios

Muthu Annamalai
Muthu Annamalai el 27 de Feb. de 2013
Editada: Muthu Annamalai el 27 de Feb. de 2013
and the documentation for textread is your friend http://www.mathworks.com/help/matlab/ref/textread.html
Walter Roberson
Walter Roberson el 27 de Feb. de 2013
Odd. What is the unicode code point of that '【' character ?

Iniciar sesión para comentar.

 Respuesta aceptada

per isakson
per isakson el 27 de Feb. de 2013
Editada: per isakson el 27 de Feb. de 2013
Study this:
function num = cssm()
str = fileread( 'cssm.txt' );
ixs = strfind( str, 'S' );
ixl = strfind( str, '056' );
ixs = ixs(1);
ixl = ixl(end);
str = str( ixs+1 : ixl+3 );
num = sscanf( str, '%d' );
end
where cssm.txt contains (copy&paste) your "file".

1 comentario

YUMENG
YUMENG el 27 de Feb. de 2013
Thank you very much! It's a nice code and it works very well!

Iniciar sesión para comentar.

Más respuestas (1)

Cedric
Cedric el 27 de Feb. de 2013
Editada: Cedric el 27 de Feb. de 2013
If your file had multiple lines like
[FROM 192.168.7.2:658161] 058 032 055 003 056 S 070 ... 056
[FROM 192.168.7.2:658161] 058 032 055 003 056 S 071 ... 056
[FROM 192.168.7.2:658161] 058 032 055 003 056 S 072 ... 056
[FROM 192.168.7.2:658161] 058 032 055 003 056 S 073 ... 056
and you wanted to generate a n_lines x n_data array of these values between S no included and last 056 entries included, for each line, you could go for something like:
buffer = fileread('exp.txt') ;
D = cell2mat(cellfun(@(m) sscanf(m, '%d'), ...
regexp(buffer, '(?<=S\s).*?(?=($|[\r\n]))', 'match'), ...
'UniformOutput', false)).' ;
Note that you would be able to build a single array of data only if S was always delimiting the same amount of data within a given file.
Cheers, Cedric

Categorías

Más información sobre Data Import and Export en Centro de ayuda y File Exchange.

Preguntada:

el 27 de Feb. de 2013

Community Treasure Hunt

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

Start Hunting!

Translated by