8

Given a 2d Numpy array, I would like to be able to compute the diagonal for each row in the fastest way possible, I'm right now using a list comprehension but I'm wondering if it can be vectorised somehow?

For example using the following M array:

M = np.random.rand(5, 3)


[[ 0.25891593  0.07299478  0.36586996]
 [ 0.30851087  0.37131459  0.16274825]
 [ 0.71061831  0.67718718  0.09562581]
 [ 0.71588836  0.76772047  0.15476079]
 [ 0.92985142  0.22263399  0.88027331]]

I would like to compute the following array:

np.array([np.diag(row) for row in M])

array([[[ 0.25891593,  0.        ,  0.        ],
        [ 0.        ,  0.07299478,  0.        ],
        [ 0.        ,  0.        ,  0.36586996]],

       [[ 0.30851087,  0.        ,  0.        ],
        [ 0.        ,  0.37131459,  0.        ],
        [ 0.        ,  0.        ,  0.16274825]],

       [[ 0.71061831,  0.        ,  0.        ],
        [ 0.        ,  0.67718718,  0.        ],
        [ 0.        ,  0.        ,  0.09562581]],

       [[ 0.71588836,  0.        ,  0.        ],
        [ 0.        ,  0.76772047,  0.        ],
        [ 0.        ,  0.        ,  0.15476079]],

       [[ 0.92985142,  0.        ,  0.        ],
        [ 0.        ,  0.22263399,  0.        ],
        [ 0.        ,  0.        ,  0.88027331]]])
3
  • 1
    There may be a good reason that you need all of those diagonal matrices, but for large n you'll be wasting a whole bunch of space. I don't know what you're doing that would make diagonal matrices preferable over a vector containing the same information, but you might want to see if there is a way to do it with the compact representation of your data.
    – jme
    Oct 22, 2014 at 16:07
  • I'm implementing a vectorised form of Von Kries chromatic adaptation transform: en.wikipedia.org/wiki/…
    – Kel Solaar
    Oct 22, 2014 at 16:16
  • 1
    Sure, so in the end if all you need is multiplication of a matrix by a diagonal matrix, that's the same as broadcasting multiplication of a vector by a matrix. Though since your matrices will only ever be 3 columns wide, you aren't wasting too much space. Just a thought.
    – jme
    Oct 22, 2014 at 16:27

2 Answers 2

12

Here's one way using element-wise multiplication of np.eye(3) (the 3x3 identity array) and a slightly re-shaped M:

>>> M = np.random.rand(5, 3)
>>> np.eye(3) * M[:,np.newaxis,:]
array([[[ 0.42527357,  0.        ,  0.        ],
        [ 0.        ,  0.17557419,  0.        ],
        [ 0.        ,  0.        ,  0.61920924]],

       [[ 0.04991268,  0.        ,  0.        ],
        [ 0.        ,  0.74000307,  0.        ],
        [ 0.        ,  0.        ,  0.34541354]],

       [[ 0.71464307,  0.        ,  0.        ],
        [ 0.        ,  0.11878955,  0.        ],
        [ 0.        ,  0.        ,  0.65411844]],

       [[ 0.01699954,  0.        ,  0.        ],
        [ 0.        ,  0.39927673,  0.        ],
        [ 0.        ,  0.        ,  0.14378892]],

       [[ 0.5209439 ,  0.        ,  0.        ],
        [ 0.        ,  0.34520876,  0.        ],
        [ 0.        ,  0.        ,  0.53862677]]])

(By "re-shaped M" I mean that the rows of M are made to face out along the z-axis rather than across the y-axis, giving M the shape (5, 1, 3).)

1
  • Brilliant, exactly what I wanted, more than 7 times faster in my use case.
    – Kel Solaar
    Oct 22, 2014 at 16:20
6

Despite the good answer of @ajcr, a much faster alternative can be achieved with fancy indexing (tested in NumPy 1.9.0):

import numpy as np

def sol0(M):
    return np.eye(M.shape[1]) * M[:,np.newaxis,:]

def sol1(M):
    b = np.zeros((M.shape[0], M.shape[1], M.shape[1]))
    diag = np.arange(M.shape[1])
    b[:, diag, diag] = M
    return b

where the timing shows this is approximately 4X faster:

M = np.random.random((1000, 3))
%timeit sol0(M)
#10000 loops, best of 3: 111 µs per loop
%timeit sol1(M)
#10000 loops, best of 3: 23.8 µs per loop
5
  • On my data with millions of rows the difference is not huge but it is still slightly faster, I will mark your answer as the accepted one. Thanks!
    – Kel Solaar
    Oct 23, 2014 at 7:46
  • 1
    @KelSolaar which version of NumPy are you using? There was a significant in fancy indexing with version 1.9.0 Oct 23, 2014 at 7:56
  • 1
    1.8.1 at the moment, most likely the reason why the speed gain is less than with your own tests.
    – Kel Solaar
    Oct 23, 2014 at 8:04
  • 1
    Good to see a quicker method (+1)! It's just a slight improvement for me too on 1.8.0: time for me to upgrade my NumPy version...
    – Alex Riley
    Oct 23, 2014 at 11:18
  • 3
    On numpy 1.8 you will probably get more bang for the buck using slicing: b = np.zeros((M.shape[0], M.shape[1]*M.shape[1])); b[:, ::M.shape[1]+1] = M; return b.reshape(M.shape[0], M.shape[1], M.shape[1]). In 1.9 the difference with Saullo's answer are very small, although it is a tad faster for very large arrays.
    – Jaime
    Oct 23, 2014 at 21:07

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.