How to convert a text file into a table properly

조회 수: 10 (최근 30일)
Shayan Taheri
Shayan Taheri 2022년 5월 11일
답변: Chunru 2022년 5월 12일
Hi,
I have text file that looks like this:
time-->data1-->data2-->data3-->...
0-->1.2,2.9,3.4-->4.6,5.5,3.2-->0.1,0.1,0.9-->...
0.1-->2.2,2.4,3.4-->4.8,5.8,3.8-->0.1,0.2,0.9-->...
...
Here, --> represents a tab.
I would like to create a table out of it so that the table look like this:
0 {1.2,2.9,3.4} {4.6,5.5,3.2} {0.1,0.1,0.9} ...
0.1 {2.2,2.4,3.4} {4.8,5.8,3.8} {0.1,0.2,0.9} ...
...
To do so, I first use readtable:
T_data = readtable('my_data.txt', 'Delimiter', '\t');
This will the create a table like this:
0 {'1.2,2.9,3.4'} {'4.6,5.5,3.2'} {'0.1,0.1,0.9'} ...
0.1 {'2.2,2.4,3.4'} {'4.8,5.8,3.8'} {'0.1,0.2,0.9'} ...
...
As you can see, each element of the table is a cell containing a string. Now I use a for loop with textscan to change the string cells into numeric cells:
for row = 1:height(T_data)
for col = 2:width(T_data)
T_data{row, col} = textscan(T_data{row, col}{1}, '%f', 'Delimiter', ',');
end
end
And it does the trick, however, the second part is very slow! (A 4200*8 table took around 10 seconds.)
I was wondering if there are alternative solutions that are more eficient.
Thank you in advance.

답변 (2개)

Chunru
Chunru 2022년 5월 12일
T = readtable('test.txt', 'Delimiter', '-->')
T = 2×4 table
time data1 data2 data3 ____ _______________ _______________ _______________ 0 {'1.2,2.9,3.4'} {'4.6,5.5,3.2'} {'0.1,0.1,0.9'} 0.1 {'2.2,2.4,3.4'} {'4.8,5.8,3.8'} {'0.1,0.2,0.9'}
for i=1:size(T,1)
for j=2:size(T,2)
T{i, j}{1} = str2num(T{i, j}{1});
end
end
T
T = 2×4 table
time data1 data2 data3 ____ ________________________ ________________________ ________________________ 0 {[1.2000 2.9000 3.4000]} {[4.6000 5.5000 3.2000]} {[0.1000 0.1000 0.9000]} 0.1 {[2.2000 2.4000 3.4000]} {[4.8000 5.8000 3.8000]} {[0.1000 0.2000 0.9000]}
  댓글 수: 1
Shayan Taheri
Shayan Taheri 2022년 5월 12일
Thank you. Yes, I have also tried this solution. But the execution time is even longer for some reason!

댓글을 달려면 로그인하십시오.


Chunru
Chunru 2022년 5월 12일
Try this:
fid = fopen('test.txt', 'r');
fgetl(fid); % skip the header
i=1;
x = [];
while ~feof(fid)
s = fgetl(fid);
tmp = textscan(s, '%f', 'Delimiter', {',', '-->'});
x = [x; tmp{1}'];
end
fclose(fid);
x
x = 2×10
0 1.2000 2.9000 3.4000 4.6000 5.5000 3.2000 0.1000 0.1000 0.9000 0.1000 2.2000 2.4000 3.4000 4.8000 5.8000 3.8000 0.1000 0.2000 0.9000

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by