Extract values from multiple txt file

Hi,
I'd like to open multiple txt files, contained in the same directory, whose names are: "file1.txt", "file2.txt", ecc...
Each file is formatted in this way: value1 value2
so two float values separated by a space.
How is it possible to put all the values in a table with two column, with one row for each files?
Thanks a lot.

 採用された回答

Stephen23
Stephen23 2022 年 11 月 16 日

1 投票

First lets create some fake data files just for testing this code:
writematrix(1:2,'file1.txt')
writematrix(3:4,'file2.txt')
writematrix(5:6,'file9.txt')
writematrix(7:8,'file10.txt')
Now lets get a list of those filenames:
P = '.'; % absolute or relative path to where the files are saved
S = dir(fullfile(P,'file*.txt'));
S = natsortfiles(S); % download from <www.mathworks.com/matlabcentral/fileexchange/47434-natural-order-filename-sort>
for k = 1:numel(S)
F = fullfile(S(k).folder,S(k).name);
V = readmatrix(F);
S(k).data = V;
end
M = vertcat(S.data)
M = 4×2
1 2 3 4 5 6 7 8

3 件のコメント

marco97f
marco97f 2022 年 11 月 17 日
Thanks, I try with the example above and it works correctly.
There is also a way to use this in the case the separator in txt files is different from " , " ?
Do I have to modify something inside the script of natsortfiles?
Stephen23
Stephen23 2022 年 11 月 17 日
編集済み: Stephen23 2022 年 11 月 17 日
"There is also a way to use this in the case the separator in txt files is different from " , " ?"
In many cases with regular text formatting READMATRIX can automagically detect the delimiter character. If it cannot (or if you simply want to make your code more robust), you can specify the DELIMITER option:
"Do I have to modify something inside the script of natsortfiles?"
I doubt it. As its documentation makes quite clear, the function NATSORTFILES sorts filenames into alphanumeric order. What would you hope to achieve by modifying it?
marco97f
marco97f 2022 年 11 月 17 日
Ok, I resolve the problem.
Thanks a lot.

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeTables についてさらに検索

製品

リリース

R2021b

質問済み:

2022 年 11 月 16 日

コメント済み:

2022 年 11 月 17 日

Community Treasure Hunt

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

Start Hunting!

Translated by