Reading Data from txt file with a unique FormatSpec
2 views (last 30 days)
Show older comments
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!!
Accepted Answer
Stephan
on 21 Aug 2019
Edited: Stephan
on 21 Aug 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 Comments
Stephan
on 21 Aug 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)
More Answers (1)
Stephen23
on 21 Aug 2019
Edited: Stephen23
on 22 Aug 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
See Also
Categories
Find more on Text Files in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!