curious
curious

Reputation: 1554

How to compute orthogonal vector in python?

I have the following code to compute the orthogonal vectors of each vector coming as input from an i,j dimension matrix. So each row in the matrix is a vector. Here is the code:

for i in range(data.shape[0]):
          for j in range(data.shape[1]):
              s=0 #row counter set to 0
              if j == data.shape[1]-1: #check if last row element has been reached
                  for k in range(j): #compute the sum of all previous values.
                      s=s+data2[i][k]*data[i][k]
                  data2[i][j] = -s/data[i][k]
              else:
                  data2[i][j] = random.uniform(1,random.getrandbits(10))
          dot(data[i],data2[i])

But it doesn't work as the dot function very rarely returns 0 which should be in case the vectors are orthogonal. I can't see a flow at the logic of my code. I simply fix j-1 random elements for the coefficients of the orthogonal vector and then in order to find the last coefficient i solve a simple equation which is the dot product of the previous coefficients of the random elements with the coefficients of the vector divided by the last coeffient. a1r1+a2r3+...+anrn=0. I know ai's. I fix random i-1 ri and then i solve the 1 var equation linear problem to find rn suth than ri vector would be orthogonal to a1 vector. The results from the last dot product computation i am getting are in this form:

===================================================
8.90285882653
===================================================
15.1275777619
===================================================
25.0847305913
===================================================
30.8608285102
===================================================
35.2496752739
===================================================
-53.3796252747
===================================================
16.302777
===================================================
29.3607765359
===================================================
-39.8982101139
===================================================
42.97222625

Upvotes: 3

Views: 8667

Answers (1)

gg349
gg349

Reputation: 22701

This works. I edited a bit your code (got rid of the var s, which is now called quotient), but the only error was in the range of k up to the total length of the vector minus 2, and not up to the second to last one element. Notice in any case that this method is not robust.

for i in range(data.shape[0]):
      for j in range(data.shape[1]):
          if j == data.shape[1]-1: #check if last row element 
              quotient=(data2[i][:-1]*data[i][:-1]).sum()
              data2[i][j] = -quotient/data[i][-1]
          else:
              data2[i][j] = random.uniform(1)
      print dot(data[i],data2[i])

Upvotes: 4

Related Questions