How to generate boxplot from data in struct

5 views (last 30 days)
Asef Islam
Asef Islam on 9 Apr 2018
Answered: Jatin on 20 Aug 2024
Let's say I have a struct that contains a bunch of arrays of data of different sizes. What is the easiest way to generate a boxplot from this data?

Answers (1)

Jatin
Jatin on 20 Aug 2024
Hi Asef Islam,
To do this, we must first format the data which can be read by the “boxplot” function. Let’s the group the data in each field using their field name, this can be done by combining all array into a single column vector.
For e.g., let's say the struct is dataStruct defined as:
%initialize dataStruct
dataStruct.field1 = rand(10, 1);
dataStruct.field2 = rand(15, 1);
dataStruct.field3 = rand(12, 1);
Using the following code boxplot can be generated from a struct with arrays as fields.
% Initialize empty arrays for data and group labels
data = [];
labels = [];
% Get the field names of the struct
fields = fieldnames(dataStruct);
% Loop through each field in the struct
for i = 1:length(fields)
% Extract the data array from the struct
cdata = dataStruct.(fields{i});
% Concatenate the array with data
data = [data; cdata];
% Create a group label array for the current data
labels = [labels; repmat({fields{i}}, length(cdata), 1)];
end
% Generate a boxplot
boxplot(data, labels);
% Adding title and labels
title('Boxplot of Struct Data');
xlabel('Data Fields');
ylabel('Values');
You can also refer to the MathWorks documentation of “boxplot” for more details:
Hope this helps.

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!