How to generate boxplot from data in struct

5 次查看(过去 30 天)
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?

回答(1 个)

Jatin
Jatin 2024-8-20
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.

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by