1

Here is my code. What I want it to return is an array of matrices

[[1,1],[1,1]], [[2,4],[8,16]], [[3,9],[27,81]]

I know I can probably do it using for loop and looping through my vector k, but I was wondering if there is a simple way that I am missing. Thanks!

from numpy import *
import numpy as np

k=np.arange(1,4,1)
print k

def exam(p):
   return np.array([[p,p**2],[p**3,p**4]])

print exam(k)

The output:

[1 2 3]

[[[ 1  2  3]

  [ 1  4  9]]

 [[ 1  8 27]

  [ 1 16 81]]]
3
  • The button with the braces on it is for code formatting. Commented Dec 23, 2013 at 6:28
  • When you say "array of matrices", what do you actually mean? A 3-dimensional ndarray? A list of matrix objects? Commented Dec 23, 2013 at 6:30
  • I think a list of matrix objects. Commented Dec 23, 2013 at 6:31

1 Answer 1

2

The key is to play with the shapes and broadcasting.

b = np.arange(1,4) # the base
e = np.arange(1,5) # the exponent

b[:,np.newaxis] ** e
=> 
array([[ 1,  1,  1,  1],
       [ 2,  4,  8, 16],
       [ 3,  9, 27, 81]])

(b[:,None] ** e).reshape(-1,2,2) 
=>
array([[[ 1,  1],
        [ 1,  1]],

       [[ 2,  4],
        [ 8, 16]],

       [[ 3,  9],
        [27, 81]]])

If you must have the output as a list of matrices, do:

m = (b[:,None] ** e).reshape(-1,2,2)
[ np.mat(a) for a in m ]
=>
[matrix([[1, 1],
        [1, 1]]),
 matrix([[ 2,  4],
        [ 8, 16]]),
 matrix([[ 3,  9],
        [27, 81]])]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.