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
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: