plot bar graph based on element type in matrix

3 views (last 30 days)
I have a 20x100 (t,N) matrix with each element being either 1, 2, or 3. I want to create a bar graph showing the amount of each type of element. so at t=20, of the 100 columns, how many have 1, how many have 2, how many have 3.
Is that possible?

Accepted Answer

Star Strider
Star Strider on 7 Oct 2024
Edited: Star Strider on 7 Oct 2024
Do you want all of them, or just the last row (t=10)?
This does both —
A = randi(3, 20, 100)
A = 20×100
2 2 1 3 1 3 3 3 1 1 1 2 2 2 1 3 3 1 1 1 2 3 3 1 2 1 2 1 2 1 2 2 3 3 1 1 3 3 3 2 3 1 1 3 2 1 1 1 2 2 1 2 1 1 3 2 3 3 3 2 3 2 3 2 2 1 3 1 2 3 3 3 3 2 2 2 1 1 2 3 2 2 3 1 1 1 1 1 1 1 2 1 3 3 3 1 1 1 3 1 3 1 2 1 1 1 1 1 1 3 1 2 2 3 3 1 3 1 1 1 2 3 3 1 3 2 1 3 1 2 3 1 2 2 1 1 1 1 2 3 1 1 1 3 2 3 1 2 3 3 1 2 2 2 2 2 1 3 2 3 3 3 3 2 2 2 3 3 2 2 3 1 2 1 1 2 3 1 1 2 3 1 2 3 2 2 3 2 3 2 2 1 1 2 3 1 3 3 1 3 2 1 3 1 1 1 3 3 2 1 1 2 2 3 1 3 1 1 3 2 3 3 3 1 3 2 1 3 3 1 3 2 2 3 3 2 2 3 1 3 1 3 1 2 2 3 2 1 3 1 2 2 2 1 1 2 2 3 2 1 1 3 3 3 1 2 3 1 3 1 1 1 3 1 2 1 1 3 2 2 3 3 2 3 2 3 1 2 1 3 1 2 1 2 1 2 1 1 2 3
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
TallyAll = accumarray(A(:), 1)
TallyAll = 3×1
675 645 680
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
ResultAll = table(TallyAll, 'RowNames',compose('%d',1:3))
ResultAll = 3x1 table
TallyAll ________ 1 675 2 645 3 680
figure
bar(1:3, TallyAll)
Tally20 = accumarray(A(20,:).', 1)
Tally20 = 3×1
35 30 35
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Result20 = table(Tally20, 'RowNames',compose('%d',1:3))
Result20 = 3x1 table
Tally20 _______ 1 35 2 30 3 35
figure
bar(1:3, Tally20)
EDIT — Forgot about the bar plots. Now added.
.
  8 Comments
Kitt
Kitt on 7 Oct 2024
That worked PERFECTLY haha!!
Thank you so much!

Sign in to comment.

More Answers (1)

dpb
dpb on 7 Oct 2024
M=randi([1 3],20,100);
whos t
[min(M(:)) max(M(:))]
ans = 1×2
1 3
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
histogram(M(20,:))
xticks(1:3)
xlabel('Bin'), ylabel('Count')
title('Counts for t=20')
  1 Comment
Kitt
Kitt on 7 Oct 2024
I've tried the histogram but the problem is I want to see the distribution over time, and when I try to plot multiple histograms they are just on top of each other and I can't really see the change

Sign in to comment.

Categories

Find more on Graph and Network Algorithms in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!