Borrar filtros
Borrar filtros

Unable to split bar graph variables

1 visualización (últimos 30 días)
Randy Lee
Randy Lee el 19 de Sept. de 2021
Respondida: Srijith Kasaragod el 22 de Sept. de 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:
'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);

Respuestas (1)

Srijith Kasaragod
Srijith Kasaragod el 22 de Sept. de 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');
Refer 'bar' documentation for more information about specifying categorical data.

Categorías

Más información sobre Line Plots en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by