Gabriel Costa
Gabriel Costa

Reputation: 11

MatLab vs Python - Vectorizing and reshaping arrays

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?

Upvotes: 1

Views: 629

Answers (2)

Salman Ghauri
Salman Ghauri

Reputation: 594

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

Upvotes: 0

ibezito
ibezito

Reputation: 5822

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])

Upvotes: 1

Related Questions