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

 採用された回答

Star Strider
Star Strider 2019 年 2 月 3 日

1 投票

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 件のコメント

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

サインインしてコメントする。

その他の回答 (0 件)

Community Treasure Hunt

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

Start Hunting!

Translated by