0

I would like to vectorize some code, but I find it hard to apply some functions to vectors of variables.

For example, I have two constant vectors, a and b, and a vector of vectors x (a matrix). Dimensions of the members of x is the same as those of a and b. I want to make matrices formed by columns from : a member of x, a, and b:

x = [[ 0.76662363 -0.0397725   0.64086377]
 [ 0.76198581 -0.04605764  0.6459538 ]]

a = [ 0.2763932   0.85065081 -0.5527864 ]

b = [-0.7236068   0.52573111 -0.5527864 ]

The output should be a vector (or array) of two 3x3 matrices. I am trying to run the following code:

a = np.column_stack((x, a, b))

however I get an error message that the dimensions do not match across the arguments:

File "/software/python/2.7.8/lib/python2.7/site-packages/numpy/lib/shape_base.py", line 317, in column_stack
    return _nx.concatenate(arrays, 1)
ValueError: all the input array dimensions except for the concatenation axis must match exactly

Any ideas?

3
  • Please add sample input and the expected output. Furthermore add the stacktrace of your error. Commented Feb 11, 2017 at 18:16
  • How do you rearrange 12 terms (2x3,3,3) into 18 terms (2 3x3)? Commented Feb 11, 2017 at 18:46
  • hpaulj, by taking 2 copies of a and b. Commented Feb 11, 2017 at 18:49

1 Answer 1

1

Going with the updated requirements:

>>> N = 2    # n cols of x.T
>>> K = 3    # x and a and b
>>> M = 3    # len(a)
>>> outstack = np.empty((N, M, K))
>>> outstack[..., 0] = x
>>> outstack[..., 1] = a[None, :]
>>> outstack[..., 2] = b[None, :]

outstack stacks two 3x3 matrices.

The trick here is preallocating the output stack. The output serves as a broadcasting reference, so a and b can be used almost unchanged and will be broadcast correctly.

Sign up to request clarification or add additional context in comments.

13 Comments

Unfortunately, this gives me a single matrix which has dimension 3 x 4, and whose two first columns are x.T, and the latter two columns are a and b. What I want is two 3x3 matrices, one for each element of x.
@John you mean you want two copies of x.T one with a joined as the third column, one with b?
No. I need two 3x3 matrices. If x1 and x2 are the two rows of x (columns of x.T), the two matrices I need are: (x1 a b) (x2 a b) The reason I need to vectorize the code is that the members of x are 10^8, instead of 2.
John - you should have put that basic information in the question the first time.
hpaulj, noted. I assumed that using the term vectorize would do the trick.
|

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.