Unable to split bar graph variables
2 views (last 30 days)
Show older comments
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:
'Heads: [some color]'
'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
heads = 0; % instantiate heads variable
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
heads = heads + 1;
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');
xlabel('Heads and Tails');
ylabel('Number of Coin Tosses');
y = [heads, tails];
bar(y);
0 Comments
Answers (1)
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.
x=categorical({'Heads and Tails'});
y=[heads,tails];
bar(x,y);
legend('Heads','Tails');
0 Comments
See Also
Categories
Find more on Line Plots in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!