How to generate boxplot from data in struct

조회 수: 5 (최근 30일)
Asef Islam
Asef Islam 2018년 4월 9일
답변: Jatin 2024년 8월 20일
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