Reading Data from txt file with a unique FormatSpec

2 vues (au cours des 30 derniers jours)
Nir Goren
Nir Goren le 21 Août 2019
Commenté : Nir Goren le 22 Août 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!!
  1 commentaire
Nir Goren
Nir Goren le 21 Août 2019
  • Sorry 12 columns - not 6 columns...
  • Thanks

Connectez-vous pour commenter.

Réponse acceptée

Stephan
Stephan le 21 Août 2019
Modifié(e) : Stephan le 21 Août 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 commentaires
Stephan
Stephan le 21 Août 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)
Nir Goren
Nir Goren le 21 Août 2019
THANKS!

Connectez-vous pour commenter.

Plus de réponses (1)

Stephen23
Stephen23 le 21 Août 2019
Modifié(e) : Stephen23 le 22 Août 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
  1 commentaire
Nir Goren
Nir Goren le 22 Août 2019
Thanks Stephen!
Very useful for me :-)

Connectez-vous pour commenter.

Community Treasure Hunt

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

Start Hunting!

Translated by