clear
disp("Binomial Distribution. Note: p must be real and 0<p<1")
p = input("p:");
n = input("n:");
hold on
for x = 1:n
C = factorial(n)/(factorial(x)*factorial(n - x));
f(x) = C*(p^x)*(1-p)^(n-x);
plot(x,f(x))
grid on
title("Binomial Distribution ")
xlabel("x")
ylabel("f(x)")
end

 Respuesta aceptada

Star Strider
Star Strider el 3 de Feb. de 2019
You need to completely vectorise your expressions and equations, specifically using element-wise operations (note the use of the ‘dot operator’ in .*, ./ and .^) in my revision of your code. This avoids the need for a for loop. (If you use a for loop, you need to subscript your variables.) I also use an anonymous function for ‘f’. See the documentation on Array vs. Matrix Operations (link) for an extended discussion, and the documentation on Anonymous Functions (link).
This works:
disp("Binomial Distribution. Note: p must be real and 0<p<1")
p = input("p:");
n = input("n:");
x = 1:n
C = factorial(n)./(factorial(x).*factorial(n - x));
f = @(x) C.*(p.^x).*(1-p).^(n-x);
plot(x,f(x))
grid on
title("Binomial Distribution ")
xlabel("x")
ylabel("f(x)")

2 comentarios

James Worden
James Worden el 3 de Feb. de 2019
Thank you so much for your help!!! It is greatly appreciated and worked like a charm!
Star Strider
Star Strider el 3 de Feb. de 2019
As always, my pleasure!

Iniciar sesión para comentar.

Más respuestas (0)

Preguntada:

el 2 de Feb. de 2019

Comentada:

el 3 de Feb. de 2019

Community Treasure Hunt

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

Start Hunting!

Translated by