Plotting rows of a specific column of similar value on separate figures

12 views (last 30 days)
Hi, I am trying to make a plot of column 3 of the table "zt" below/attached. However, I need one plot per column 1 value. i.e.Under column 1, I want a plot for 1, a plot for 2, a plot for 3...and finally a plot for 6. I want matlab to go through the table and look for similar values in column 1 and then plot its corresponding column 3 values then goes to the next. For example, for "1", it counts 8 rows then plots its column 3 data. Next for "2", it counts 4 rows then plots its column 3 data. Next for "3", it counts 3 rows then plots it column 3 data and so on till it gets to "6".
The problem with my code is that p is not iterating correctly and I don't know how to fix it. It should normally go from 1<->8 for "1", then 9<->12 for "2", then 13<->15 for "3"......till it gets to 6
close all;clc
for i=1:6
% [p]=p+p
zt table below and attached
1 2 3
1 3 4
1 5 5
1 5 5
1 5 5
1 7 4
1 5 4
1 4 5
2 6 2
2 4 4
2 4 8
2 5 9
3 6 7
3 1 10
3 6 1
4 4 5
4 5 1
4 5 5
5 2 5
5 6 6
5 5 4
6 4 8
6 3 9
6 5 2
6 6 6

Accepted Answer

dpb on 12 Aug 2022
When you want a new figure for every one, that pretty-much means splitapply isn't going to be all that handy because you can't define an anonymous function that has more than one line --and you've got to have at least two for the new figure followed by plot. You can write a small inline function and call that, of course, but if doing that, may as well just do it inline -- but you can still use findgroups although as you've discovered, unique works as well or as well could discretize
for i=1:numel(id)
plot(D(D(:,1)==id(i),3),'DisplayName',"Group "+id(i))
Virtually the same code you had; splitapply or rowfun for a table just do the lookup indexing for you -- but they're doing the same thing inside, it's just "syntactic sugar" to save you the trouble writing the indexing expression. But, the price for ease is the above -- you can't include more code than one line in an anonymous function so if your needs are more than can be done that way, you have to write another function anyway.

More Answers (1)

dpb on 12 Aug 2022
Try something like
hAx=axes;hold on
legend("Group "+unique(g))
If you really, really want each on a totally separate figure/axes, then you'll have to use a loop and extract those for which
for the loop construct over g.
mpz on 12 Aug 2022
Edited: mpz on 12 Aug 2022
@dpb I was able to come up with a different method which is different from what I wanted. See below. I would still like to know how to do it the way you showing.
clc;close all
une = unique(D(:,1)); % identifies all the unique elements in column 1 of D
sep = cell(numel(une), 1); % sums all the elements identified above and builds a cell
for i=1:numel(une)
index = D(:,1)==une(i);
sep{i} = D(index, 2:3);

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!