Ourania
Ourania

Reputation: 29

Not enough input arguments in function

I have a function of this form

    function [g] = g(i,j)
    k=1;

    if i==0
       g=0;
    elseif i==k
       g=j;
    end

And I don't want the second line in the code. Instead I want the function to read k from the main program. I don't want to write

    function [g] = g(i,j,k) 

instead, because in this way I will have to write g as a function of i,j and k in the code of the main program. Is there another way ?

Upvotes: 1

Views: 59

Answers (1)

Dan
Dan

Reputation: 45752

You can use an anonymous function to create a closure. Define your function as

function [g] = g(i,j,k)
    if i==0
       g=0;
    elseif i==k
       g=j;
    end
end

And then in your main script you can do something like

k=1;
g2 = @(i,j)g(i,j,k);

And now you can call g2 the way you were calling g before but k will be 1 and it will be defined in your main script instead of in your function.

Or you could even skip k completely and define:

g1 = @(i,j)g(i,j,1)

Upvotes: 3

Related Questions