Reputation: 4352
I want to write an inline function which will accept two arguments in which one argument is a vector.
>>nCk = @(n,k)(nchoosek(n,k));
>>nCk(3,1:2)
Error using nchoosek (line 29)
The second input has to be a non-negative integer.
How can I make the second argument accepts a vector.
Upvotes: 1
Views: 696
Reputation: 3428
While its probably not what you want, I think this is one situation where I would use a for loop, as nchoosek only accepts an integer for its k
value:
nCk = @(n,k)(nchoosek(n,k));
n = 3;
for k = 1:2
disp(nCk(n,k));
end
Though if you do it this way, then the inline statement is likely redundant, so it could be reduced to:
n = 3;
for k = 1:2
disp(nchoosek(n,k));
end
Upvotes: 3
Reputation: 74940
As mentioned, nchoosek
only allows integer inputs for the second argument. If you do want to make an inline function, you can fold the loop into a call to arrayfun
, however:
nCk = @(n,kVec)arrayfun(@(k)nchoosek(n,k),kVec);
And use like this:
nCk(5,0:5)
ans =
1 5 10 10 5 1
Upvotes: 8