How can I get three plots from a struct array which is split by three categories?
조회 수: 2 (최근 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!
댓글 수: 0
채택된 답변
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.
Reference - Find Array Elements That Meet a Condition
댓글 수: 0
추가 답변 (1개)
Gyan Vaibhav
2024년 1월 29일
편집: Gyan Vaibhav
2024년 1월 29일
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
Gyan Vaibhav
2024년 1월 29일
@Paul Böckmann I have edited the above answer to my understanding of your question.
Let me know if you have some doubts.
참고 항목
카테고리
Help Center 및 File Exchange에서 Line Plots에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!