How to ensure matrix/array shape when performing slicing and other operations in Python? -


i have been running interesting problem when performing operations on matrices , arrays in python. i'm converting code matlab python , quirk of python generating significant amount of bugs in code.

for example:

say want perform operation in python nx1 array

import numpy np numpy.random import randn  ... n = 50  u = np.cumprod(rand(n,1))**(1.0/np.arange(n,0,-1)) 

rather getting element wise power of 2 arrays resulting in vector, massive matrix , not example,

on inspection found example shape of np.arange(..).shape in case (n,) null dimension size, if slice matrix eg.

x[:,3].shape = (n,) 

and rather getting 2 column matrices multiplied broadcasting assumes want matrix when multiplying (n,1)*(n,) = (n,n) when want = (n,1)

how can perform these operations , ensure dimensions? i.e. want able top slice matrix , column vector or find np.cumprod() or np.cumsum() in 1 dimension of matrix , vector..

to avoid broadcasting, inputs need match in shape.

thus giving both parts single shape, e.g. (5,):

np.random.randn(5)**(1.0/np.arange(5,0,-1)) 

produces result of same shape:

array([        nan,         nan,  0.9643002 ,         nan,  0.55951515]) 

making both (5,1) ensures output (5,1).

np.random.randn(5,1)**(1.0/np.arange(5,0,-1).reshape(5,1)) array([[        nan],        [        nan],        [ 0.83152719],        [        nan],        [ 1.64430971]]) 

a key difference when moving matlab there has atleast 2 dim.

np.atleast_2d might if bothered 1d arrays. adds singleton dimensions @ front end needed.

np.atleast_2d(np.arange(5))  # (1,5) array # array([[0, 1, 2, 3, 4]]) 

np.array has ndmin optional parameter, acting same way.

np.array(np.arange(5),ndmin=2) 

that raises difference. matlab prefers added dimensions @ end. numpy readily @ beginning.

these produce same (5,5) array:

np.ones((5,1))*np.ones(5) np.ones((5,1))*np.ones((1,5)) np.ones((5,5))*np.ones((5,5)) 

octave has added numpy broadcasting matlab syntax.


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

order - Notification for user in user account opencart -