Problem in properly creating a structure to store data

1 Ansicht (letzte 30 Tage)
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!

Akzeptierte Antwort

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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Tags

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by