Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is a general strategy for solving this kind of problem.</p> <p>First, write a small script, with the loop written explicitly in two different functions, and a test at the end making sure that the two functions are exactly the same:</p> <pre><code>import numpy as np from numpy import newaxis def explicit(a): n = a.shape[0] m = np.zeros_like(a) for k in range(n): for i in range(n): for j in range(n): m[k,i] += a[i,j] - a[i,k] - a[k,j] + a[k,k] return m def implicit(a): n = a.shape[0] m = np.zeros_like(a) for k in range(n): for i in range(n): for j in range(n): m[k,i] += a[i,j] - a[i,k] - a[k,j] + a[k,k] return m a = np.random.randn(10,10) assert np.allclose(explicit(a), implicit(a), atol=1e-10, rtol=0.) </code></pre> <p>Then, vectorize the function step by step by editing <code>implicit</code>, running the script at each step to make sure that they continue staying the same:</p> <p>Step 1</p> <pre><code>def implicit(a): n = a.shape[0] m = np.zeros_like(a) for k in range(n): for i in range(n): m[k,i] = (a[i,:] - a[k,:]).sum() - n*a[i,k] + n*a[k,k] return m </code></pre> <p>Step 2</p> <pre><code>def implicit(a): n = a.shape[0] m = np.zeros_like(a) m = - n*a.T + n*np.diag(a)[:,newaxis] for k in range(n): for i in range(n): m[k,i] += (a[i,:] - a[k,:]).sum() return m </code></pre> <p>Step 3</p> <pre><code>def implicit(a): n = a.shape[0] m = np.zeros_like(a) m = - n*a.T + n*np.diag(a)[:,newaxis] m += (a.T[newaxis,...] - a[...,newaxis]).sum(1) return m </code></pre> <p>Et voila'! No loops in the last one. To vectorize that kind of equations, <a href="http://www.scipy.org/EricsBroadcastingDoc" rel="noreferrer">broadcasting</a> is the way to go!</p> <p>Warning: make sure that <code>explicit</code> is the equation that you wanted to vectorize. I wasn't sure if the terms that do not depend on <code>j</code> should also be summed over.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload