Vinod
Vinod

Reputation: 4352

How to write a inline function which will accept two arguments in MATLAB

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

Answers (3)

Ayb4btu
Ayb4btu

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

Jonas
Jonas

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

George
George

Reputation: 5691

From here ,you can see that you can have as vector the first argument and not the second.

So ,you can use:

nCk = @(k,n)(nchoosek(k,n));

If that helps you of course

Upvotes: 0

Related Questions