Octave/matlab, multiple default arguments defined by constant

1.5k Views Asked by At

I have a problem with defining default arguments to a function in Octave/Matlab by a previously defined constant. Could someone give me a hint, why in the following code test1(1) displays 1 and 100, while test2(1) fails with error:testarg' undefined near line 1 column 36`? Thank you so much!

testarg = 100

function test1 (arg1=testarg, arg2=100)
 disp(arg1)
 disp(arg2)
endfunction

function test2 (arg1=testarg, arg2=testarg)
 disp(arg1)
 disp(arg2)
endfunction

test1(1)
test2(2)

Edit:

Please not that the order of the arguments matters:

function test3 (arg1=100, arg2=testarg)
 disp(arg1)
 disp(arg2)
endfunction

 octave:8> test1(1)
 1
 100
 octave:9>test3(1)
 error: `testarg' undefined near line 1 column 32
2

There are 2 best solutions below

2
On

I've never seen that syntax in Matlab, is it an Octave thing? In general default arguments need to be a constant rather than some other variable that may or may not be in scope or initialised at the time the function is called (feel free to educate me on languages where this isn't the case, of course).

The 'normal' way to do default arguments in regular Matlab is like this:

function test1(arg1, arg2)
    if nargin < 2
        arg2 = 100;
    end
    if nargin < 1
        arg2 = testarg;     % if testarg isn't in scope this still won't work
    end
    disp(arg1);
    disp(arg2);
end
0
On

This looks like a bug to me, you should report it to the Octave developers.

In the meanwhile, here is a workaround:

testarg = 100

function test1 (arg1, arg2)
 if nargin < 2, arg2 = 100; end
 if nargin < 1, arg1 = testarg; end

 disp(arg1)
 disp(arg2)
endfunction

test1(2)

That said, it is better to be explicit here, and define them as "global variables". If the testarg is intended as a constant, better make it a function that returns said value:

testarg = @() 100;