'How to define a default vector/matrix for a function's input

I would like to create a function in which one of the inputs is a matrix. But I also want the function to have a default input. For example, please see the following simple "test" function with an input "x":

def test(x=None):
    if x==None:
        y = np.array([[123], [123]])
    else:
        y = x
    return y

In this way, let's say I want to see the function without providing input:

 print(test())

Would give:

[[123]
 [123]]

However, if I want "x" to be a matrix or vector (like the following script):

  z = np.array([[12], [12]])
  print(test(z)

I got an error saying:

**"The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()".**

Fine, I want to comply with the error warning. Then I changed the function to:

 def test(x=None):
     if x.all()==None:
         y = np.array([[123], [123]])
     else:
         y = x
     return y

Would return (as expected):

 print(test())
 [[123]
  [123]]

However, with the revised script, if I want x to be none again:

 print(test())

Gives a new warning:

 **'NoneType' object has no attribute 'all'**

How can I solve this? I want the function to work either with x being a pre-defined matrix or not (a default).



Solution 1:[1]

You can use default parameter, then if no argument is provided it will be used

def test(x=np.array([[123], [123]])):
    return  x

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tomáš Šturm