Question

I am attempting to subtract two zero ranked numpy arrays a and b. I would like a-b to return an error when they are not of the same size. For example, if shape(a)=[300,] and shape(b)=[450,]; a-b returns an array of shape[300,450]. I would instead like the program to return an error.

Was it helpful?

Solution

You could try this approach:

def mySubtract(a, b):
    if a is None or b is None or a.shape != b.shape:
       sys.stderr.write("a and b don't have the same shape!\n")
       raise ValueError("a and b don't have same shape!")
    return a-b

I wasn't sure what you meant by "return an error", but if you prefer to just return an invalid result rather than raising a ValueError exception, you could instead just return None or return "a and b don't have the same shape!".

Keep in mind that the caller of your routine would need to know what to do with these special error return codes. So in general exception might be a cleaner approach.

OTHER TIPS

You probably want to look into exceptions. Here is some pseudocode that should point you on the right track:

if a.size() != b.size():
    raise Exception("Invalid sizes")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top