0

I have an m by n matrix A, implemented as a numpy array.

import numpy as np
m = 10
n = 7
A = np.random.rand(m, n)

I want to compute the m by m matrix B whose entries are

B[i, j] = sum_{k=1,...,n} sum_{l=1,...,n} A[i, k] * A[j, l]

What is the easiest way to do this without making explicit for loops?

6
  • Show your loopy code? Commented May 6, 2018 at 8:35
  • @Divakar See edit. Commented May 6, 2018 at 8:42
  • .. A.dot(A.T)? Commented May 6, 2018 at 8:44
  • @SimonParker the code in your edit does not compute sum_{k} sum_{l} A[i, k] * A[j, l], but sum_{k} A[i, k] * A[j, k], which @Divakar's A.dot(A.T) gives you. Commented May 6, 2018 at 8:50
  • @AlbertoGarcia-Raboso That's a mistake. The first version was the good one. I will erase it. Commented May 6, 2018 at 8:51

1 Answer 1

2

Notice that the sum over k in your expression only affects the first factor, while the sum over l only involves the second:

sum_{k=1,...,n} sum_{l=1,...,n} A[i, k] * A[j, l] =
    (sum_{k=1,...,n}  A[i, k]) * (sum_{l=1,...,n} A[j, l])

The expressions in parentheses are, except for the names of the indices, the same, so define

sA = np.sum(A, axis=1)

Then your B is the so-called outer product of sA with itself:

B = np.outer(sA, sA)
Sign up to request clarification or add additional context in comments.

Comments

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.