MATLAB Answers

0

Reading Data from txt file with a unique FormatSpec

Asked by Nir Goren on 21 Aug 2019 at 8:48
Latest activity Commented on by Nir Goren on 22 Aug 2019 at 10:45
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 Comment

  • Sorry 12 columns - not 6 columns...
  • Thanks

Sign in to comment.

2 Answers

Answer by Stephan
on 21 Aug 2019 at 9:41
Edited by Stephan
on 21 Aug 2019 at 9:42
 Accepted Answer

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 Comments

Thanks Stephan!
Cool and elegant solution :-)
Do you have an idea how to do the same with functions available in R2016b verison?
Cheers!
Nir
Stephan
on 21 Aug 2019 at 12:49
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)
THANKS!

Sign in to comment.


Answer by Stephen Cobeldick on 21 Aug 2019 at 15:19
Edited by Stephen Cobeldick on 22 Aug 2019 at 8:40

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 Comment

Thanks Stephen!
Very useful for me :-)

Sign in to comment.