3

Suppose we have the matrix A:

A = [1,2,3
     4,5,6
     7,8,9]

I want to know if there is a way to obtain:

B = [1,2,3
     4,5,6
     7,8,9
     7,8,9]

As well as:

B = [1,2,3,3
     4,5,6,6
     7,8,9,9]

This is because the function I want to implement is the following:

U(i,j) = min(A(i+1,j)^2, A(i,j)^2)
V(i,j) = min(A(i,j+1)^2, A(i,j)^2)

And the numpy.minimum seems to need two arrays with equal shapes.

My idea is the following:

np.minimum(np.square(A[1:]), np.square(A[:]))

but it will fail.

2 Answers 2

2

For your particular example you could use numpy.hstack and numpy.vstack:

In [11]: np.vstack((A, A[-1]))
Out[11]: 
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9],
       [7, 8, 9]])

In [12]: np.hstack((A, A[:, [-1]]))
Out[12]: 
array([[1, 2, 3, 3],
       [4, 5, 6, 6],
       [7, 8, 9, 9]])

An alternative to the last one is np.hstack((A, np.atleast_2d(A[:,-1]).T)) or np.vstack((A.T, A.T[-1])).T): you can't hstack a (3,) array to a (3,3) one without putting the elements in the rows of a (3,1) array.

Sign up to request clarification or add additional context in comments.

2 Comments

What about np.hstack((A, A[:, [2]]))
@UttamPal Good suggestion! I've edited in this approach in a slightly more general form as the prefered one.
2

A good answer to your literal question is provided by @xnx, but I wonder whether what you actually need is something else.

This type of question comes up a lot in comparisons, and the usual solution is to take only the valid entries, rather than using a misaligned comparison. That is, something like this is common:

import numpy as np

A = np.arange(9).reshape((3,3))

U = np.minimum(A[1:,:]**2, A[:-1,:]**2)
V = np.minimum(A[:,1:]**2, A[:,:-1]**2)

print U
# [[ 0  1  4]
#  [ 9 16 25]]

print V
# [[ 0  1]
#  [ 9 16]
#  [36 49]]

I suspect that you're probably thinking, "that's a hassle, now U and V have different shapes than A, which is not what I want". But, to this I'd say, "yes, it is a hassle, but it's better to deal with the problem up front and directly than hide it within an invalid row of an array."

A standard example and typical use case of this approach would be numpy.diff, where, "the shape of the output is the same as a except along axis where the dimension is smaller by n."

2 Comments

Thank you for your advice. Let me see if I catch it: Do you mean I have to do something like np.minimum(A[1:], A[:-1]) and repeat the last row after that?
Yes, exactly. I wrote the wrong expression. I'll fix it now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.