Extract specific field names and associated data from a structure
6 views (last 30 days)
Show older comments
Dear all,
here is a screenshot of my structure I created using following code:
file = 'myfile';
struct = dir (fullfile (file, '*.xlsx'));
for i = 1:numel (struct);
F = fullfile (file, struct(i).name);
[struct(i).num, struct(i).txt, struct(i).raw] = xlsread (F); % insert .num, .txt. and .raw into the structure
end
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/719069/image.png)
Attached you find the data for one .xlsx file. It is possible for me to extract the fields seperaly using:
x = struct(1).num (8:14, 3:end); % extract position 1 field .num; extract only row 8.14 and column 3:end
Know I want to extract all positions with 'bf_s' simultaniously using a if statement to analyse the data for each condition seperatly to calculate single and mean values.
Thank you for your support!
Regards, Jonas
0 Comments
Accepted Answer
Stephen23
on 23 Aug 2021
Edited: Stephen23
on 23 Aug 2021
Rather than using an IF it would be simpler to specify an appropriate filename for DIR:
P = 'myfile';
S = dir(fullfile(P,'*bf_s.xlsx')); % specify BF_S here
for k = 1:numel(S);
F = fullfile(P,S(k).name);
[S(k).num, S(k).txt, S(k).raw] = xlsread(F);
S(k).ext = S(k).num(8:14,3:end);
end
You can loop over S or use the methods shown here:
Is there a particular reason why you want to use XLSREAD and not READMATRIX/READTABLE ?
2 Comments
Stephen23
on 24 Aug 2021
Edited: Stephen23
on 24 Aug 2021
"Too many output arguments and I can't fix that bug. Usually it is trivial. But I don't get it."
Did you read the documentation for the functions that you are trying to use?
XLSREAD has three outputs.
READTABLE and READCELL and READMATRIX all have just one output.
So if you swap XLSREAD (like in your question and my answer) with three outputs for a function that only has one output, then obviously you can only call it with that one output that the function supports.
"So far I have to specify DIR for three filenames (bf_s, nb_s and ob_s) in three lines of code: Is there a more clever solution?"
If the code for for processing the files is exactly/mostly the same, then you can simply concatenate the DIR output together before the loop:
P = 'myfile';
S = vertcat(... Do NOT use STRUCT as a variable name!
dir(fullfile(P, '*bf_s.xlsx')),...
dir(fullfile(P, '*nb_s.xlsx')),...
);
for k = 1:numel(S)
.. etc.
end
Do NOT name your variable STRUCT, as this shadows the very important inbuilt STRUCT function.
More Answers (0)
See Also
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!