简体   繁体   中英

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 ?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM