Why wont my plot graph a line?

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

 采纳的回答

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 个评论

Thank you so much for your help!!! It is greatly appreciated and worked like a charm!
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