On Thu, Apr 7, 2016 at 3:39 AM, Irvin Probst <irvin.pro...@ensta-bretagne.fr > wrote:
> On 06/04/2016 04:11, Todd wrote: > > When you try to transpose a 1D array, it does nothing. This is the > correct behavior, since it transposing a 1D array is meaningless. However, > this can often lead to unexpected errors since this is rarely what you > want. You can convert the array to 2D, using `np.atleast_2d` or > `arr[None]`, but this makes simple linear algebra computations more > difficult. > > I propose adding an argument to transpose, perhaps called `expand` or > `expanddim`, which if `True` (it is `False` by default) will force the > array to be at least 2D. A shortcut property, `ndarray.T2`, would be the > same as `ndarray.transpose(True)` > > Hello, > My two cents here, I've seen hundreds of people (literally hundreds) > stumbling on this .T trick with 1D vectors when they were trying to do some > linear algebra with numpy so at first I had the same feeling as you. But > the real issue was that *all* these people were coming from matlab and > expected numpy to behave the same way. Once the logic behind 1D vectors was > explained it made sense to most of them and there were no more problems. > > The problem isn't necessarily understanding, although that is a problem. The bigger problem is having to jump through hoops to do basic matrix math. > And by the way I don't see any way to tell apart a 1D "row vector" from a > 1D "column vector", think of a code mixing a Rn=>R jacobian matrix and some > data supposed to be used as measurements in a linear system, so we have > J=np.array([1,2,3,4]) and B=np.array([5,6,7,8]), what would the output of > J.T2 and B.T2 be ? > > As I said elsewhere, we already have a convention for this established by `np.atleast_2d`. 1D arrays are treated as row vectors. `np.hstack` and `np.vstack` also treat 1D arrays as row vectors. So `arr.T2` will follow this convention, being equivalent to `np.atleast_2d(arr).T`. > I think it's much better to get used to writing > J=np.array([1,2,3,4]).reshape(1,4) and B=np.array([5,6,7,8]).reshape(4,1), > then you can use .T and @ without any verbosity and at least if forces > users (read "my students" here) to think twice before writing some linear > algebra nonsense. > > That works okay when you know beforehand what the shape of the array is (although it may very well be the different between a simple, 1-line piece of code and a 3-line piece of code). But what if you try to turn this into a general-purpose function? Then any function that has linear algebra needs to call `atleast_2d` on every value used in that linear algebra, or use `if` tests. And if you forget, it may not be obvious until much later depending on what you initially use the function for and what you use it for later.
_______________________________________________ NumPy-Discussion mailing list NumPy-Discussion@scipy.org https://mail.scipy.org/mailman/listinfo/numpy-discussion