[Numpy-discussion] fastest way to do multiplication with diagonal matrices from left or right

Pietro Berkes berkes@gatsby.ucl.ac...
Mon Mar 26 11:55:47 CDT 2007


This is a small function I use to speed up multiplication with diagonal
matrices. I don't know if it's the *fastest* way to do it, but it's
pretty fast.

def mult_diag(d, mtx, left=True):
    """Multiply a full matrix by a diagonal matrix.
    This function should always be faster than dot.

    Input:
      d -- 1D (N,) array (contains the diagonal elements)
      mtx -- 2D (N,N) array

    Output:
      mult_diag(d, mts, left=True) == dot(diag(d), mtx)
      mult_diag(d, mts, left=False) == dot(mtx, diag(d))
    """
    if left:
        return (d*mtx.T).T
    else:
        return d*mtx


On Fri, 23 Mar 2007, daniel.egloff@zkb.ch wrote:

> 
> 
> Dear list
> 
> what is the fastet way to multiply with a diagonal matrix from left or
> right and without to build a square matrix from the diagonal.
> Here it what I am looking for:
> 
> import numpy as N
> 
> def diagmult(X, Y):
>     """
>     Matrix multiplication X*Y where either X or Y is a diagonal matrix.
>     """
>     if X.ndim == 1 and Y.ndim == 2:
>         R = Y.copy()
>         for i, d in enumerate(X):
>             R[i,:] *= d
>         return R
>     elif X.ndim == 2 and Y.ndim == 1:
>         R = X.copy()
>         for i, d in enumerate(Y):
>             R[:,i] *= d
>         return R
>     elif X.ndim == 1 and Y.ndim == 1:
>         return X*Y
>     else
>         raise ValueError('diagmult dimension mismatch X.ndim = %d, Y.ndim =
> %d' % (X.ndim, Y.ndim))
> 
> Freundliche Grüsse
> Daniel Egloff
> Zürcher Kantonalbank
> Leiter(in) Financial Computing, ZEF
> 
> Josefstrasse 222, 8005 Zürich
> Telefon 044 292 45 33, Fax 044 292 45 95
> Briefadresse: Postfach, 8010 Zürich, http://www.zkb.ch
> ___________________________________________________________________
> 
> Disclaimer:
> 
> 
> Diese Mitteilung ist nur fuer die Empfaengerin / den Empfaenger bestimmt.
> 
> Fuer den Fall, dass sie von nichtberechtigten Personen empfangen wird,
> bitten wir diese hoeflich, die Mitteilung an die ZKB zurueckzusenden und
> anschliessend die Mitteilung mit allen Anhaengen sowie allfaellige Kopien
> zu vernichten bzw. zu loeschen. Der Gebrauch der Information ist verboten.
> 
> 
> This message is intended only for the named recipient and may contain
> confidential or privileged information.
> 
> If you have received it in error, please advise the sender by return e-mail
> and delete this message and any attachments. Any unauthorised use or
> dissemination of this information is strictly prohibited.


More information about the Numpy-discussion mailing list