1

Consider three different MatLab arrays: a, b and c. All of them are equally sized arrays. Let's say, 64 x 64. Now, in order to re-organize the elements of one of these arrays in form of a one-dimension vector inside another array, X, I can do the following:

X = [X a(:)];

Now, I have a 4096 x 1 array. If I want to have an array with that contains in each column the elements of different arrays, I can just repeat the process above for b and c.

Is there an equivalent of this in Python?

3
  • numpy.ndarray.flatten() and numpy.ndarray.vstack()? And this answer has a comparison of ways to flatten a 2D array in python. Commented Apr 3, 2018 at 6:47
  • size(a(:))` is (4096,1). A column vector. Not quite the same as a 1d numpy array. [a(:), b(:), c(:)] will be (4096,3). In numpy do you want (3, 4096) or (4096,3) array? numpy is C ordered (by default), MATLAB F ordered. Commented Apr 3, 2018 at 7:12
  • I want a (4096,3) array. Thanks for the replies, they helped me solving my problem! I used np.vstack and that gave me an (3,4096) array. Then just got the tranpose of the resulting array and it worked! Thanks! X=np.vstack((X,Itmp.flatten(1))) X=np.transpose(X) Commented Apr 3, 2018 at 7:28

2 Answers 2

1

You can use np.concatanate function. Example:

import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.array([7,8,9])
res = np.concatenate([a,b,c])

It is also possible to do it sequentially as follows:

res = a
res = np.concatenate([res,b])
res = np.concatenate([res,c])

result:

res = array([1, 2, 3, 4, 5, 6, 7, 8, 9])
Sign up to request clarification or add additional context in comments.

Comments

0

In order to achieve 4x1, you can use reshape() function is this way:

np.reshape((-1, 1))

a = np.zeros((2,2)) #creates 2,2 matrix
print(a.shape) #2,2
print(a.reshape((-1, 1)) #4,1

This will make sure that you achieve 1 column in resulting array irrespective of the row elements which is set to -1.

As mentioned in the comment, you can use numpy's flatten() function which make you matrix flat into a vector. E.g; if you have a 2x2 matrix, flatten() will make it to 1x4 vector.

a = np.zeros((2,2)) # creates 2,2 matrix

print(a.shape) # 2,2
print(a.flatten()) # 1,4

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.