I've never used Matlab before and I really don't know how to fix the code. I need to plot log(1000 over k) with k going from 1 to 1000.
y = @(x) log(nchoosek(1000,x));
fplot(y,[1 1000]);
Error:
Warning: Function behaves unexpectedly on array inputs. To improve performance, properly
vectorize your function to return an output with the same size and shape as the input
arguments.
In matlab.graphics.function.FunctionLine>getFunction
In matlab.graphics.function.FunctionLine/updateFunction
In matlab.graphics.function.FunctionLine/set.Function_I
In matlab.graphics.function.FunctionLine/set.Function
In matlab.graphics.function.FunctionLine
In fplot>singleFplot (line 241)
In fplot>@(f)singleFplot(cax,{f},limits,extraOpts,args) (line 196)
In fplot>vectorizeFplot (line 196)
In fplot (line 166)
In P1 (line 5)
There are several problems with the code:
nchoosek
does not vectorize on the second input, that is, it does not accept an array as input. fplot
works faster for vectorized functions. Otherwise it can be used, but it issues a warning.nchoosek
is close to overflowing for such large values of the first input. For example, nchoosek(1000,500)
gives 2.702882409454366e+299
, and issues a warning.nchoosek
expects integer inputs. fplot
uses in general non-integer values within the specified limits, and so nchoosek
issues an error.You can solve these three issues exploiting the relationship between the factorial and the gamma function and the fact that Matlab has gammaln
, which directly computes the logarithm of the gamma function:
n = 1000;
y = @(x) gammaln(n+1)-gammaln(x+1)-gammaln(n-x+1);
fplot(y,[1 1000]);
Note that you get a plot with y values for all x in the specified range, but actually the binomial coefficient is only defined for non-negative integers.