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?

Miki
  • 40,887
  • 13
  • 123
  • 202
  • [`numpy.ndarray.flatten()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.html#numpy-ndarray-flatten) and [`numpy.ndarray.vstack()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html#numpy-vstack)? And [this answer](https://stackoverflow.com/a/45323085/8944057) has a comparison of ways to flatten a 2D array in python. – eugenhu Apr 03 '18 at 06: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. – hpaulj Apr 03 '18 at 07: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) – Gabriel Costa Apr 03 '18 at 07:28

2 Answers2

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])
ibezito
  • 5,782
  • 2
  • 22
  • 46
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
Salman Ghauri
  • 574
  • 1
  • 5
  • 16