Import several tables from one txt file in Matlab

30 ビュー (過去 30 日間)
Alex Kashuba
Alex Kashuba 2021 年 3 月 26 日
コメント済み: Tessa van Kol 2023 年 2 月 27 日
Hi All!
I'm trying to read several tables from one text file in Matlab. The format can be a bit adjusted, but the principle of the file structure is this:
#TableID tab01
Length Width
1 2
3 4
#TableID tab02
Weight Volume Density
10 20 0.5
30 40 0.75
50 100 0.5
I tried to follow this article "Import Block of Mixed Data from Text File into Table or Cell Array", but detectImportOptions always thinks it's one table. The DelimitedTextImportOptions object seems to support multiple sections for the DataLines property (see help), but I can't find the way to do it with detectImportOptions.
The long story short: How can I (preferably using detectImportOptions and not writing my own code) import the given text file, detect tables IDs, autodetect variables names for both tables, and get two tables themselves, i.e.
1 2
3 4
and
10 20 0.5
30 40 0.75
50 100 0.5
Thanks a lot in advance!
P.S. This example is no good for me, while a) no auto detection from variables names, b) no auto detection of the matrices separation (look which output he expects).

採用された回答

Stephen23
Stephen23 2021 年 3 月 26 日
編集済み: Stephen23 2021 年 3 月 26 日
str = fileread('temp.txt');
tkn = regexp(str,'^#TableID[^\n]*\s*([^\n]+)([^#]*)','lineanchors','tokens');
tkn = vertcat(tkn{:});
nml = size(tkn,1);
out = cell(1,nml);
for k = 1:nml
hdr = regexp(tkn{k,1},'\S+','match');
mat = sscanf(tkn{k,2},'%f',[numel(hdr),Inf]).';
out{k} = array2table(mat,'VariableNames',hdr);
end
Checking:
out{1}
ans = 2×2 table
Length Width ______ _____ 1 2 3 4
out{2}
ans = 3×3 table
Weight Volume Density ______ ______ _______ 10 20 0.5 30 40 0.75 50 100 0.5
  4 件のコメント
Stephen23
Stephen23 2023 年 2 月 24 日
@Tessa van Kol: please upload a sample file by clicking the paperclip button.
What should the TITLE table contain?
Tessa van Kol
Tessa van Kol 2023 年 2 月 27 日
I posted my question and sample file in here How to overwrite matrix in txt file with another matrix?. Maybe @Stephen23 can help me with that?

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by