# numpy performance and list comprehension

Robert Kern robert.kern at gmail.com
Tue Apr 3 13:30:13 EDT 2007

```TG wrote:
> Hi there.
>
> Reading the page on python performance ( http://scipy.org/PerformancePython
> ) made me realize that I can achieve tremendous code acceleration with
> numpy just by using "u[:,:]" kind of syntax the clever way.
>
> Here is a little problem (Oja's rule of synaptic plasticity)
>
> * W is a matrix containing the weights of connections between elements
> i
> and j
> * V is an array containing the values of elements
>
> I want to make W evolve with this rule :
>
> dW[i,j] / dt = alpha * (V[i] * V[j] - W[i,j] * V[i]^2)
>
> (don't pay attention to the derivate and stuff)
>
> So, how would you write it in this nifty clever way ?

irstas is correct. I'm just going to show off another feature of numpy,
numpy.newaxis.

import numpy as np

V = np.array([1, 2, 3])
VT = V[:, np.newaxis]      # VT.shape == (3, 1)

W = np.array([[1,2,3], [4,5,6], [7,8,9]])

dWdt = alpha * VT*(V - W*VT)

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco

```