How can I get three plots from a struct array which is split by three categories?

3 次查看(过去 30 天)
Say I have a struct array which looks like the following:
How would I go about creating a figure with three datalines A, B and C as seen in the following (disregarding the style)?
There are seperate arrays with the categories (A B C) and the x- Values (1 2 3 4).
Of course, in this simple example I could just plot rows (1:4), (5:8) and (9:12), but my real project has many more rows per category.
I've tried searching for other answers, but wasn't able to find any (probably lack of correct search terms), so feel free to point me to the duplicate question, if applicable.
Thank you so much in advance!

采纳的回答

Dyuman Joshi
Dyuman Joshi 2024-1-29
编辑:Dyuman Joshi 2024-1-29
Use a for loop to go through each unique category and utilize logical indexing to obtain and plot the corresponding data.

更多回答(1 个)

Gyan Vaibhav
Gyan Vaibhav 2024-1-29
编辑:Gyan Vaibhav 2024-1-29
此 个回答 已被 Paul Böckmann 标记
Hi Paul,
I have assumed that you only have 3 categories. Here I try to seperate the (x,y) pairs in arrays on the basis of the category and plot them.
Here is a sample code for your sample data:
% Assuming your data is stored as such
data = [
struct('category', 'A', 'x', 1, 'y', 234),
struct('category', 'B', 'x', 1, 'y', 260),
struct('category', 'C', 'x', 1, 'y', 212),
struct('category', 'A', 'x', 2, 'y', 549),
struct('category', 'B', 'x', 2, 'y', 354),
struct('category', 'C', 'x', 2, 'y', 400),
struct('category', 'A', 'x', 3, 'y', 300),
struct('category', 'B', 'x', 3, 'y', 467),
struct('category', 'C', 'x', 3, 'y', 943)
];
% Initialize arrays for each category assuming you have only 3 you can use
xA = [];
yA = [];
xB = [];
yB = [];
xC = [];
yC = [];
% Populate the arrays with x and y values
% if the total number of values is known please initialize array of that
% size for better performance
for i = 1:length(data)
switch data(i).category
case 'A'
xA(end+1) = data(i).x;
yA(end+1) = data(i).y;
case 'B'
xB(end+1) = data(i).x;
yB(end+1) = data(i).y;
case 'C'
xC(end+1) = data(i).x;
yC(end+1) = data(i).y;
end
end
figure;
hold on;
% Plot the data for each category
plot(xA, yA, 'r', 'DisplayName', 'A');
plot(xB, yB, 'g', 'DisplayName', 'B');
plot(xC, yC, 'b', 'DisplayName', 'C');
% Add legend to the plot
legend('show');
hold off;
I hope this is what you were looking for. Make changes as per your real data.
Thanks
Gyan
  3 个评论
Paul Böckmann
Paul Böckmann 2024-1-29
Hi,
  1. there are not. Any x-y pair will be unique in their respective category, and there won't be any values without a corresponding "partner".
  2. In the scope of this question, only one array will be relevant

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

产品


版本

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by