How to extract specific struct data from multiple mat files? Please help. Thank you so much.

I have the following 5 mat files for 5 samples of data type 0. These mat files contain lot of data structure and variables. I want to extract a specific struct type data named ap_struct from each these mat files using loop. How can I do that? Thank you so much.

 Accepted Answer

N = 5;
ap_structs = cell(N,1);
for K = 1 : N
filename = K + "pbs0.mat";
datastruct = load(filename, 'ap_struct');
ap_structs{K} = datastruct.ap_struct;
end
%output is cell array ap_structs
Here, I do not assume that the ap_struct in the different files have exactly the same fields in exactly the same order.
If they do contain the same fields in the same order then instead you can use
N = 5;
clear ap_struct;
for K = N : -1 : 1
filename = K + "pbs0.mat";
datastruct = load(filename, 'ap_struct');
ap_struct(K) = datastruct.ap_struct;
end
%output is non-scalar struct ap_struct

7 Comments

Hi, Walter thank you but I want output as a single stacked structure combining all those 5 structure together one after another. Not as a cell. Could you kindly help me with this?
Are the fields of the different ap_struct all completely different from between the differerent files? If so, then Yes, that is possible. But if any two field names in any of the files are the same, then it is not possible to create a stacked struct "one after the other" -- not without renaming the field names that duplicate the others.
If all of the field names are exactly the same for the different files, then I would firmly recommend that you do not go for a stacked struct, and instead use a non-scalar struct, in which case the second block of code I posted above is already the solution.
Hi Walter I have the following struct for each of those struct. Now how can I stack those together one after another as a single output? The final structure dimension should be 1x50 with 1 field of varying length of column vectors.
N = 5;
ap_struct = struct('times', {});
for K = 1 : N
filename = K + "pbs0.mat";
datastruct = load(filename, 'ap_struct');
ap_struct = [ap_struct; datastruct.ap_struct];
end
Hi Walter I want output structure dimension 1x50 with 1 field of varying length of column vectors. But I got the following one with your code
N = 5;
ap_struct = struct('times', {});
for K = 1 : N
filename = K + "pbs0.mat";
datastruct = load(filename, 'ap_struct');
ap_struct = [ap_struct, datastruct.ap_struct];
end

Sign in to comment.

More Answers (0)

Asked:

sam
on 21 Sep 2022

Commented:

sam
on 21 Sep 2022

Community Treasure Hunt

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

Start Hunting!