Plotting rows of a specific column of similar value on separate figures
조회 수: 5 (최근 30일)
이전 댓글 표시
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=0;
p=sum(zt{:,1}==i)
figure(i)
i
% [p]=p+p
plot(zt{[1:p],3})
end
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
댓글 수: 0
채택된 답변
dpb
2022년 8월 12일
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
D=table2array(B);
[g,id]=findgroups(D(:,1));
for i=1:numel(id)
figure
plot(D(D(:,1)==id(i),3),'DisplayName',"Group "+id(i))
end
legend
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.
댓글 수: 0
추가 답변 (1개)
dpb
2022년 8월 12일
Try something like
g=findgroups(zt(:,1));
hAx=axes;hold on
splitapply(@(y)plot(y),zt(:,3),g)
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
plot(zt(zt(:,1)==g(i),3))
for the loop construct over g.
댓글 수: 4
참고 항목
카테고리
Help Center 및 File Exchange에서 Tables에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!