Como leio em uma série de números usando "TextScan" no MATLAB se o arquivo for principalmente texto?

StackOverflow https://stackoverflow.com/questions/3620079

  •  26-09-2019
  •  | 
  •  

Pergunta

Eu tenho um arquivo de texto com uma sequência de 3 números que eu preciso ler no MATLAB.

Por exemplo:

#######################
#
#
#    Text Text Text
#
#
#######################

Blah blah blah = ####
Blah blah blah = ####
Blah blah blah = ####
Blah blah blah = ####
Blah blah blah = ####
Blah blah blah = ####


I_NEED_THIS_STRING =  1234.5 6789.0 1234.5 !Comment blah blah blah

Eu preciso ler nesses 3 números em uma matriz.

POR FAVOR AJUDE.

Obrigado

Foi útil?

Solução

Se a maior parte do arquivo for irrelevante para o seu aplicativo, sugiro pré -processamento com sua linguagem de script favorita ou ferramenta de linha de comando para encontrar as linhas relevantes e usar o textScan () nisso.

por exemplo, de um prompt de shell:

grep ^I_NEED_THIS_STRING infile > outfile

em Matlab:

fid = fopen('outfile');
C = textscan(fid, 'I_NEED_THIS_STRING = %f %f %f')
fclose(fid)

Veja o Documentação do TextScan para mais detalhes.

Outras dicas

Uma alternativa é usar IMPORTAR DADOS Para ler o arquivo inteiro em uma matriz celular de cordas (com uma linha por célula), use Strmatch Para encontrar a célula que contém a string 'I_NEED_THIS_STRING', então use Sscanf Para extrair os 3 valores dessa célula:

>> data = importdata('mostly_useless_text.txt','\n');  %# Load the data
>> index = strmatch('I_NEED_THIS_STRING',data);  %# Find the index of the cell
                                                 %#   containing the string
>> values = sscanf(data{index},'I_NEED_THIS_STRING = %f %f %f')  %# Read values

values =

  1.0e+003 *

    1.2345
    6.7890
    1.2345

Se o arquivo potencialmente tem muito de texto inútil antes ou depois da linha em que você está interessado, você pode usar muita memória no MATLAB carregando tudo em uma variável. Você pode evitar isso carregando e analisando uma linha de cada vez usando um loop e a função Fgets:

fid = fopen('mostly_useless_text.txt','r');  %# Open the file
newLine = fgets(fid);                        %# Get the first line
while newLine ~= -1                          %# While EOF hasn't been reached
  if strmatch('I_NEED_THIS_STRING',newLine)  %# Test for a match
    values = sscanf(newLine,'I_NEED_THIS_STRING = %f %f %f');  %# Read values
    break                                    %# Exit the loop
  end
  newLine = fgets(fid);                      %# Get the next line
end
fclose(fid);                                 %# Close the file
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top