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!