How to avoid duplicate struct fields when loading structs

8 views (last 30 days)
I am writing a code to automate some data processing. For this, I load in several files containing structs. I'd like to combine these structs as fields in a struct called "Data". Each file is named according to the date it was obtained.
The code is able to produce the struct with all data inside, but the structure of the struct is not as desired. For example, instead of "Data.D20190501.datainstruct" it becomes "Data.D20190501.D20190501.datainstruct". Can the desired format be achieved?
% Day strings to use in file names.
d = ["01"; "10"; "13"; "15"];
% Take files out of every folder (Day #n)
for n = 1:3
% Define path per day. (name of the struct in the file)
main = sprintf('D201905%s', d(n+1));
% Load all combined datasets.
Data.(main) = load(sprintf('../path/Day %d/file', n));
end

Accepted Answer

Stephen23
Stephen23 on 3 Jun 2019
Edited: Stephen23 on 3 Jun 2019
It appears that the variables inside the .mat files were unfortunately also named using the dates, rather than simply using one fixed name for all of the files (which would simplify the file importing code). Here is one solution:
S = load(...);
Data.(main) = S.(main);
If the variable name in the file does not match main then this code will fail. If there is only one variable in each file then you can import this variable regardless of its name:
C = strut2cell(load(...));
Data.(main) = C{1};
Note that forcing meta-data (such as dates) into variable or fieldnames results in fragile, slow, and complex code to process that data. Meta-data is data its own right, and should be stored in a variable, rather than in the name of a field or variable. For example, your data would likely be better stored in a non-scalar structure:
S(1).data = [...]
S(1).name = 'D20190501.mat';
S(2).data = [...]
S(2).name = 'D20190503.mat';
...
  1 Comment
OswinH
OswinH on 3 Jun 2019
Thank you for your quick and well explained answer! This fixed the issue and I've gained some further insight into working with structs in data processing. I am glad to make use of your feedback.

Sign in to comment.

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!