Problem in properly creating a structure to store data

1 visualizzazione (ultimi 30 giorni)
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!

Risposta accettata

Stephen23
Stephen23 il 10 Gen 2022
Modificato: Stephen23 il 10 Gen 2022
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 Commenti
Vasileios Vachtsevanos
Vasileios Vachtsevanos il 19 Gen 2022
Thank you very much for this thorough answer and examples :) .
Stephen23
Stephen23 il 19 Gen 2022
@Vasileios Vachtsevanos: my pleasure! Please remember to click accept if my answer helped you!

Accedi per commentare.

Più risposte (0)

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by