Effacer les filtres
Effacer les filtres

How to generate boxplot from data in struct

12 vues (au cours des 30 derniers jours)
Asef Islam
Asef Islam le 9 Avr 2018
Réponse apportée : Jatin Singh le 20 Août 2024 à 11:40
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?

Réponses (1)

Jatin Singh
Jatin Singh le 20 Août 2024 à 11:40
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.

Community Treasure Hunt

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

Start Hunting!

Translated by