Problem in properly creating a structure to store data

1 回表示 (過去 30 日間)
Vasileios Vachtsevanos
Vasileios Vachtsevanos 2022 年 1 月 10 日
コメント済み: Stephen23 2022 年 1 月 19 日
Hello everyone,
I have created a number of different data files (in .txt) form. I would like to import them inside a larger structure before I save the enviroment, however I face a problem when constructing it.
In the past had come across a solution that would allow me to create a structure (Let's say S) but I am currently unable to locate it. Based on a similar algorithm I found (Importing multiple text files into MATLAB - (mathworks.com)) I can import all dataset within a structure, but in order for me to call a specific one I need to call with the `expression S.data(i)`. This mean that I should create a table for all different conditions of each one of the ~430 datasets, in order to remember which condition corresponds to which value of `i`.
I was hoping to be able to dynamically name the subgroups within the structure in order ot use the `S.dataset_name' format. Is there any way to achieve it without messing a lot with IOPS time?
Thanks in advance!

採用された回答

Stephen23
Stephen23 2022 年 1 月 10 日
編集済み: Stephen23 2022 年 1 月 10 日
The simple and efficient approach:
P = 'absolute or relative path to where the files are saved';
S = dir(fullfile(P,'*.txt'));
for k = 1:numel(S)
F = fullfile(P,S(k).name);
S(k).data = readtable(F); % or whatever function you use to import the filedata
end
"This mean that I should create a table for all different conditions of each one of the ~430 datasets, in order to remember which condition corresponds to which value of `i`."
No, you don't need to "create a table" for that, the structure S already contains all of that information, e.g. for the 2nd file:
S(2).data % gives the imported data
S(2).name % gives the filename (dataset)
"I was hoping to be able to dynamically name the subgroups within the structure in order ot use the `S.dataset_name' format."
Of course you can use dynamic fieldnames:
It will be more complex, fragile, liable to bugs (consider what happens if the filenames contain characters that are not valid in fieldnames) and offers no obvious benefit:
P = 'absolute or relative path to where the files are saved';
S = dir(fullfile(P,'*.txt'));
D = struct();
for k = 1:numel(S)
F = fullfile(P,S(k).name);
[~,N,~] = fileparts(S(k).name);
G = sprintf('complicated_%s',N);
D.(G) = readtable(F); % or whatever function you use to import the filedata
end
  2 件のコメント
Vasileios Vachtsevanos
Vasileios Vachtsevanos 2022 年 1 月 19 日
Thank you very much for this thorough answer and examples :) .
Stephen23
Stephen23 2022 年 1 月 19 日
@Vasileios Vachtsevanos: my pleasure! Please remember to click accept if my answer helped you!

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

その他の回答 (0 件)

カテゴリ

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

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by