# Unable to split bar graph variables

4 views (last 30 days)
Randy Lee on 19 Sep 2021
Answered: Srijith Kasaragod on 22 Sep 2021
I have the output that I need for a simple heads or tails program. What I tried to do was split up the two bar graphs but everytime I go to plot, it graphs it as one variable so I can't change colors of the two bar graphs or add a legend that says:
'Tails: [a different color]'
Additionally, I can't seem to label the heads or tails bar graphs. I attached a .png file of the resulting graph.
% Using MATLAB, write a program to simulate a coin toss.
% Your code will record tossing the coin 100 times (randomly).
% Then, calculate the percentage of heads (or 1) and tails (or 0) generated by your random function.
% Finally, create a bar chart to display the results.
% n = 100
N = 100; % number of trials
tails = 0; % instantiate tails variable
i = 0; % instatiate i variable to iterate N times
while i < N
coinToss = randi([0,1]); % -1 = tails, 1 = heads
if coinToss == 0
elseif coinToss == 1
tails = tails + 1;
else
disp('Error, invalid coin toss.')
end
i = i + 1;
end
grid on;
title('Simulation of a Coin Toss where N = 100');
ylabel('Number of Coin Tosses');
bar(y);

Srijith Kasaragod on 22 Sep 2021
Following lines of code shows one possible solution to your problem. The bar graph is created against a categorical value on the x-axis. In that case, heads and tails would be plotted as two variables.
bar(x,y);