← numpy-100

Added Expert 4

ebf21a3c6896b2d1ae20ebf26f9d8807fd91b3af · Nicolas Rougier · Jun 8, 2014 20:21

+50 · 2 files changed

  • README.ipynb +31 −0
  • README.rst +19 −0
diff --git a/README.ipynb b/README.ipynb
index 9798aab..64db89e 100644
--- a/README.ipynb
+++ b/README.ipynb
@@ -1199,6 +1199,37 @@
      "metadata": {},
      "outputs": []
     },
+    {
+     "cell_type": "markdown",
+     "metadata": {},
+     "source": [
+      "Consider a set of p matrices wich shape (n,n) and a set of p vectors\n",
+      "with shape (n,1). How to compute the sum of of the p matrix products at\n",
+      "once ? (result has shape (n,1))\n"
+     ]
+    },
+    {
+     "cell_type": "code",
+     "collapsed": false,
+     "input": [
+      "# St\u00e9fan van der Walt\n",
+      "\n",
+      "p, n = 10, 20\n",
+      "M = np.ones((p,n,n))\n",
+      "V = np.ones((p,n,1))\n",
+      "S = np.tensordot(M, V, axes=[[0, 2], [0, 1]])\n",
+      "print S\n",
+      "\n",
+      "# It works, because:\n",
+      "# M is (P, N, N)\n",
+      "# V is (P, N, 1)\n",
+      "# Thus, summing over the paired axes 0 and 0 (of M and V independently),\n",
+      "# and 2 and 1, to remain with a Mx1 vector."
+     ],
+     "language": "python",
+     "metadata": {},
+     "outputs": []
+    },
     {
      "cell_type": "heading",
      "level": 2,
diff --git a/README.rst b/README.rst
index db30715..5bd41d5 100644
--- a/README.rst
+++ b/README.rst
@@ -628,6 +628,25 @@ Expert
       S[2,3] = 42
       print S
 
+4. Consider a set of p matrices wich shape (n,n) and a set of p vectors with shape (n,1).
+   How to compute the sum of of the p matrix products at once ? (result has shape (n,1))
+
+   .. code-block:: python
+
+      # Stéfan van der Walt
+
+      p, n = 10, 20
+      M = np.ones((p,n,n))
+      V = np.ones((p,n,1))
+      S = np.tensordot(M, V, axes=[[0, 2], [0, 1]])
+      print S
+
+      # It works, because:
+      # M is (P, N, N)
+      # V is (P, N, 1)
+      # Thus, summing over the paired axes 0 and 0 (of M and V independently),
+      # and 2 and 1, to remain with a Mx1 vector.
+
 
 Master
 ======