I have the following array in NumPy:
A = array([1, 2, 3])
How can I obtain the following matrices (without an explicit loop)?
B = [ 1 1 1
2 2 2
3 3 3 ]
C = [ 1 2 3
1 2 3
1 2 3 ]
Thanks!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Edit2: The OP asks in the comments how to compute
I can think of two ways. I like this way because it generalizes easily:
The idea is to use
np.ogrid. This defines a list of two numpy arrays, one of shape (3,1) and one of shape (1,3):grid[0]can be used as a proxy for the indexi, andgrid[1]can be used as a proxy for the indexj.So everywhere in the expression
l(i, i) + l(j, j) - 2 * l(i, j), you simply replacei–>grid[0], andj–>grid[1], and numpy broadcasting takes care of the rest:However, in this particular case, since
l(i,i)andl(j,j)are just the diagonal elements ofl, you could do this instead:d[np.newaxis,:]pumps up the shape ofdto (1,3), andd[:,np.newaxis]pumps up the shape ofdto (3,1).Numpy broadcasting pumps up
d[np.newaxis,:]andd[:,np.newaxis]to shape (3,3), copying values as appropriate.Edit1: Usually you do not need to form
BorC. The purpose of Numpy broadcasting is to allow you to useAin place ofBorC. If you show us how you plan to useBorC, we might be able to show you how to do the same withAand numpy broadcasting.(Original answer):
or
From the dirty tricks department:
But note that these are views of
A, not copies (as were the solutions above). ChangingB, altersA: