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

 Akzeptierte Antwort

Star Strider
Star Strider am 3 Feb. 2019

1 Stimme

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 Kommentare

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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by