MATLAB: How to find the maximum and minimum value(s) of the randomly generated bar chart, and set a specific color for the max and min value(s)

barbarchartchart;colormaxminvalue

The code itself is a dicethrow-simulation. Basically, you choose a number between 1 and infinity, which will be the amount of times 1 dice will be thrown. Let's say 20 throws. Afterwards, a barchart will appear with the amount of times every dice-eye has been thrown out of the 20 throws. What I want to do, is put the lowest bar(s) to a red color, and the highest bar(s) to a green color. I've put some code in comment-form to show what I've come up with so far. I really hope somebody can help me out.
Thanks in advance!
j=input("choose a number of throws: ");
throws=zeros(1,6);
for s=1:j
k=randi(6);
throws(k)=throws(k)+1;
% if throws==min(throws)
%




% color = 'r';
%
% elseif throws==max(throws)
%
% color = 'g';
%
% else
%
% color = 'b';
end
bar(throws)
number_of_dices=1;
yoffset=0.1*number_of_dices;
for i=1:numel(throws)
text(i, throws(i)+yoffset, num2str(throws(i)),'HorizontalAlignment',...
'center','VerticalAlignment','bottom')
end
if j<6
set(gca,'YTick',1:j)
ylim([0 j])
end
set(gca,'Fontsize', 15)
xlabel('Number of eyes pr. 1 dice')
ylabel(['Number of outcomes out of ', num2str(j), ' throws'])
ylim([0 j])
end

Best Answer

The code below puts 2 extra bar plots with the desired colors. It also avoids loops.
%n_throws=input("choose a number of throws: ");
n_throws=20;
n_throws=max(1,floor(n_throws));%round the input to an integer >=1
throws=accumarray(randi(6,n_throws,1),ones(1,n_throws),[6 1]);
[~,minind]=min(throws);
[maxval,maxind]=max(throws);
bar(throws)
hold on
bar(minind,throws(minind),'r')
bar(maxind,throws(maxind),'g')
hold off
ylim([0 ceil(maxval*1.1)])
xlim([0 7])
set(gca,'YTick',1:n_throws)
set(gca,'Fontsize', 15)
xlabel('Number of eyes pr. 1 dice')
ylabel(sprintf('Number of outcomes out of %d throws',n_throws))