Filter löschen
Filter löschen

Unable to split bar graph variables

1 Ansicht (letzte 30 Tage)
Randy Lee
Randy Lee am 19 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:
'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);

Antworten (1)

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

Kategorien

Mehr zu Line Plots finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by