[SciPy-User] scalars vs array of length 1

Sturla Molden sturla@molden...
Thu Jul 8 15:30:31 CDT 2010


Victor Eijkhout skrev:
> I want to write a function that can accept both a scalar and a vector, when called on a vector it should return a vector of scalar application results. However, scalars seem to be treated differently from length-1 lists.
>
>   
Is Matlab syntax is confusing you?

In Python, length-1 containers and scalars are not the same.

Lists:

 >>> a = [1,2,3,4]
 >>> print a
[1, 2, 3, 4]
 >>> print a[0]
1
 >>> print a[0:1]
[1]
 >>> print a[0:0]
[]

NumPy does the same:

 >>> import numpy as np
 >>> a = np.array([1,2,3,4])
 >>> print a
[1 2 3 4]
 >>> print a[0]
1
 >>> print a[0:1]
[1]
 >>> print a[0:0]
[]

 >>> a
array([1, 2, 3, 4])
 >>> type(a[0])
<type 'numpy.int32'>
 >>> type(a[0:1])
<type 'numpy.ndarray'>

You can use the function np.isscalar to check if an argument is scalar.



Sturla





















> %%%%% input
>
> from numpy import array,matrix,cos,sin,tan
>
> def f(x):
>     valueMatrix = array([cos(x),sin(x),tan(x)])
>     print valueMatrix.shape
>     valueMatrix = matrix(valueMatrix)
>     print valueMatrix.shape
>     print 
>
> print "scalars"
> f(5)
> f([5])
>
> %%% output
>
> scalars
> (3,)
> (1, 3)
>
> (3, 1)
> (3, 1)
>
> %%%%
>
> How do I get that shape to be the same in both cases?
>
> Victor.
>
> _______________________________________________
> SciPy-User mailing list
> SciPy-User@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>   



More information about the SciPy-User mailing list