MATLAB: Wont the plot graph a line

help

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

Best Answer

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)")