[SciPy-User] Using scipy matrices for low-dimensional problems

Warren Weckesser warren.weckesser at gmail.com
Thu Mar 6 21:09:48 EST 2014


On 3/6/14, Mannucci, Anthony J (335G) <anthony.j.mannucci at jpl.nasa.gov> wrote:
> I want to write a least squares solver or Kalman filter that can handle
> varying numbers of parameters, including just one. I have found this fails
> in the scipy routines (e.g. linalg.lstsq). The reason appears to be that 1x1
> matrices (or arrays) are not considered matrices. I believe a 1x1 matrix can
> be viewed as a legitimate square matrix. Is there a workaround that would
> permit me to use 1x1 matrices in my calculations? Scipy now complains that I
> have not passed in a matrix and will not apply the algorithm. Thank you.
>


Tony,

This works for me:

In [28]: from scipy.linalg import lstsq

In [29]: a = np.array([[2.0]])

In [30]: b = np.array([1.0])

In [31]: lstsq(a, b)
Out[31]: (array([ 0.5]), array([], dtype=float64), 1, array([ 2.]))

In [32]: import scipy

In [33]: scipy.__version__
Out[33]: '0.13.2'


It will not work if `a` is not explicitly a 2-dimensional array.  E.g.


In [38]: a = np.array([2.0])  # This is not a 2D array!

In [39]: lstsq(a, b)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-39-007204d270f7> in <module>()
----> 1 lstsq(a, b)

/home/warren/anaconda/lib/python2.7/site-packages/scipy/linalg/basic.pyc
in lstsq(a, b, cond, overwrite_a, overwrite_b, check_finite)
    509         a1,b1 = map(np.asarray, (a,b))
    510     if len(a1.shape) != 2:
--> 511         raise ValueError('expected matrix')
    512     m, n = a1.shape
    513     if len(b1.shape) == 2:

ValueError: expected matrix


So be sure `a` is really 2-dimensional.


Warren




> -Tony
>
> --
> Tony Mannucci
> Supervisor, Ionospheric and Atmospheric Remote Sensing Group
>  Mail-Stop 138-308,                     Tel > (818) 354-1699
>  Jet Propulsion Laboratory,              Fax > (818) 393-5115
>  California Institute of Technology,     Email > Tony.Mannucci at jpl.nasa.gov
>  4800 Oak Grove Drive,
> http://scienceandtechnology.jpl.nasa.gov/people/a_mannucci/
>  Pasadena, CA 91109
>
>



More information about the SciPy-User mailing list