Home > Enterprise >  Writing a Transpose a vector in python
Writing a Transpose a vector in python

Time:01-24

I have to write a python function where i need to compute the vector For A is n by n and xn is n by 1

r_n = Axn - (xn^TAxn)xn

Im using numpy but .T doesn't work on vectors and when I just do

r_n = A@xn - (xn@A@xn)@xn but xn@A@xn gives me a scaler.

I've tried changing the A with the xn but nothing seems to work.

CodePudding user response:

Making a 3x1 numpy array like this...

import numpy as np
       
a = np.array([1, 2, 3])

...and then attempting to take its transpose like this...

a_transpose = a.T

...will, confusingly, return this:

# [1 2 3]

If you want to define a (column) vector whose transpose you can meaningfully take, and get a row vector in return, you need to define it like this:

a = np.reshape(np.array([1, 2, 3]), (3, 1))

print(a)

# [[1]
#  [2]
#  [3]]

a_transpose = a.T

print(a_transpose)

# [[1 2 3]]

If you want to define a 1 x n array whose transpose you can take to get an n x 1 array, you can do it like this:

a = np.array([[1, 2, 3]])

and then get its transpose by calling a.T.

CodePudding user response:

If A is (n,n) and xn is (n,1):

A@xn - (xn@A@xn)@xn

(n,n)@(n,1) - ((n,1)@(n,n)@(n,1)) @ (n,1)
(n,1)          error (1 does not match n)

If xn@A@xn gives scalar that's because xn is (n,) shape; as per np.matmul docs that's a 2d with two 1d arrays

(n,)@(n,n)@(n,) => (n,)@(n,) -> scalar

I think you want

(1,n) @ (n,n) @ (n,1) => (1,1)

Come to think of it that (1,1) array should be same single values as the scalar.

Sample calculation; 1st with the (n,) shape:

In [6]: A = np.arange(1,10).reshape(3,3); x = np.arange(1,4)

In [7]: A@x
Out[7]: array([14, 32, 50])    # (3,3)@(3,)=>(3,)

In [8]: x@A@x         # scalar
Out[8]: 228

In [9]: (x@A@x)@x
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[9], line 1
----> 1 (x@A@x)@x

ValueError: matmul: Input operand 0 does not have enough dimensions (has 0, gufunc core with signature (n?,k),(k,m?)->(n?,m?) requires 1)

matmul does not like to work with scalars. But we can use np.dot instead, or simply multiply:

In [10]: (x@A@x)*x
Out[10]: array([228, 456, 684])     # (3,)

In [11]: A@x - (x@A@x)*x
Out[11]: array([-214, -424, -634])

Change the array to (3,1):

In [12]: xn = x[:,None]; xn.shape
Out[12]: (3, 1)

In [13]: A@xn - (xn.T@A@xn)*xn
Out[13]: 
array([[-214],
       [-424],
       [-634]])         # same numbers but in (3,1) shape
  • Related