How to generate boxplot from data in struct
6 次查看(过去 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?
0 个评论
回答(1 个)
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!