Reading Data from txt file with a unique FormatSpec
2 次查看(过去 30 天)
显示 更早的评论
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!!
采纳的回答
Stephan
2019-8-21
编辑:Stephan
2019-8-21
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 个评论
Stephan
2019-8-21
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)
更多回答(1 个)
Stephen23
2019-8-21
编辑:Stephen23
2019-8-22
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!