Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't broadcast input array from shape (3,1) into shape (3,)

Tags:

python

numpy

import numpy as np

def qrhouse(A):
    (m,n) = A.shape
    R = A
    V = np.zeros((m,n))
    for k in range(0,min(m-1,n)):
        x = R[k:m,k]
        x.shape = (m-k,1)
        v = x + np.sin(x[0])*np.linalg.norm(x.T)*np.eye(m-k,1)
        V[k:m,k] = v
        R[k:m,k:n] = R[k:m,k:n]-(2*v)*(np.transpose(v)*R[k:m,k:n])/(np.transpose(v)*v)
    R = np.triu(R[0:n,0:n])     
    return V, R

A = np.array( [[1,1,2],[4,3,1],[1,6,6]] )
print qrhouse(A) 

It's qr factorization code, but I don't know why error happens. The value error happens in V[k:m,k] = v

value error :
could not broadcast input array from shape (3,1) into shape (3) 
like image 544
Colin Avatar asked Oct 03 '16 04:10

Colin


2 Answers

V[k:m,k] = v; v has shape (3,1), but the target is (3,). k:m is a 3 term slice; k is a scalar.

Try using v.ravel(). Or V[k:m,[k]].

But also understand why v has its shape.

like image 58
hpaulj Avatar answered Sep 17 '22 07:09

hpaulj


Another solution that would work is V[k:m,k:k+1] = v.

k:k+1 is a 1 term slice, making the target shape (3,1).

This seems like a better solution since you do not have to modify the input array.

like image 32
Daniel Peterson Avatar answered Sep 17 '22 07:09

Daniel Peterson