Reading Data from txt file with a unique FormatSpec

4 visualizaciones (últimos 30 días)
Nir Goren
Nir Goren el 21 de Ag. de 2019
Comentada: Nir Goren el 22 de Ag. de 2019
Hello,
I have a text file containing the data in the format - [[0,0,0,0,0,-3,0,0,0,0,0,-1],[0.025,0.025,0.025,0.025,0.025,-1,-1,-1,-1,-1,-1,-1],..N*[ ]... ,[0,0,0,0,0,-3,0,0,0,0,0,-1]]
and I need to read it into a 6 columns matrix.
What is the right function and FormatSpec to use?
I am struggeling with the FormatSpec...
THANKS!!

Respuesta aceptada

Stephan
Stephan el 21 de Ag. de 2019
Editada: Stephan el 21 de Ag. de 2019
One way:
A = reshape(double(replace(string(readcell('Test.txt')),["[[", "[", "]", "]]"],["", "", "", ""])),[],12)
This uses the attached example file baesd on your question.
Result:
A =
0 0 0 0 0.0250 0.0250 -1.0000 -1.0000 0 0 0 0
0 0 0 0 0.0250 0.0250 -1.0000 -1.0000 0 0 0 0
0 -3.0000 0 -1.0000 0.0250 -1.0000 -1.0000 -1.0000 0 -3.0000 0 -1.0000
  3 comentarios
Stephan
Stephan el 21 de Ag. de 2019
As far as i can see, it would be needed to replace readcell by another function - all other stuff is available in 2016b - this should work:
A = reshape(double(split(replace(string(fileread('Test.txt')),["[[", "[", "]", "]]"],["", "", "", ""]),",",2)),[],12)

Iniciar sesión para comentar.

Más respuestas (1)

Stephen23
Stephen23 el 21 de Ag. de 2019
Editada: Stephen23 el 22 de Ag. de 2019
Method one: fileread and regexp and str2double:
>> S = fileread('Test.txt');
>> M = reshape(str2double(regexp(S,'[+-]?\d*\.?\d+','match')),12,[]).'
M =
0 0 0 0 0 -3.0000 0 0 0 0 0 -1.0000
0.0250 0.0250 0.0250 0.0250 0.0250 -1.0000 -1.0000 -1.0000 -1.0000 -1.0000 -1.0000 -1.0000
0 0 0 0 0 -3.0000 0 0 0 0 0 -1.0000
Method two: textscan (probably more efficient):
opt = {'Delimiter',',','EndOfLine','[','HeaderLines',2,'CollectOutput',true};
fmt = [repmat('%f',1,12),'],'];
[fid,msg] = fopen('Test.txt','rt');
assert(fid>=3,msg)
C = textscan(fid,fmt,opt{:});
fclose(fid);
M = C{1}
Giving:
M =
0 0 0 0 0 -3.0000 0 0 0 0 0 -1.0000
0.0250 0.0250 0.0250 0.0250 0.0250 -1.0000 -1.0000 -1.0000 -1.0000 -1.0000 -1.0000 -1.0000
0 0 0 0 0 -3.0000 0 0 0 0 0 -1.0000

Community Treasure Hunt

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

Start Hunting!

Translated by