2016-12-07 47 views
0

我有一個叫做A的維(3,n)的2d矩陣,我想計算兩個數組(b,z)的歸一化和叉積, (請參閱代碼)每列(第一列,然後第二列等)。從2d數組中獲得列來計算python中的歸一化和叉積

讓的說,A是:

A=[[-0.00022939 -0.04265404 0.00022939] 
 
[ 0.   -0.2096513 0.  ] 
 
[ 0.00026388 0.00465183 0.00026388]]
如何可以採取第一列從A(-0.00022939,O.,0.00026388)並且在下面的函數中使用它,則取然後第二列,... n列

def vectors(b): 
    b = b/np.sqrt(np.sum(b**2.,axis=0)) 
    b = b/np.linalg.norm(b)  
    z = np.array([0.,0.,1.]) 
    n1 = np.cross(z,b,axis=0) 
    n1 = n1/np.linalg.norm(n1) ## normalize n 

    return [n1] 

n1 = vectors(A) 

我該如何製作一個選擇第一列並進行計算的循環,然後是第二列等等。任何幫助!預先感謝

+0

任何幫助,請! –

+0

我建議你添加一個樣本矩陣'A'並顯示你所期望的結果。請詳細說明你想要的東西。我不明白。 –

+0

@ mr.bjerre,我已經完成了整個矩陣,它有效,但我想使用第一列,然後第二個,...直到n列 –

回答

1

這取決於你如何設置你的陣列開始。我喜歡使用numpy數組,因爲我發現索引容易讓我頭腦發熱。我認爲下面的代碼就是你以後的代碼。因爲你總是有3個colulmns,所以A不需要多長時間,你可以將它分成3列。

import numpy as np 

A=np.array([[-0.00022939, -0.04265404, 0.00022939], 
      [-0.00022939, -0.04265404, 0.00022939], 
      [0., -0.2096513, 0.], 
      [0.00026388, 0.00465183, 0.00026388]]) 

for idx in range(3): 

    b = A[:, idx] 
    print b # call your function here 

編輯::全面實施顯示代碼&輸出

import numpy as np 

def vectors(b): 
    b = b/np.sqrt(np.sum(b**2.,axis=0)) 
    b = b/np.linalg.norm(b)  
    z = np.array([0.,0.,1.]) 
    n1 = np.cross(z,b,axis=0) 
    n1 = n1/np.linalg.norm(n1) ## normalize n 

    return [n1] 

A=np.array([[-0.00022939, -0.04265404, 0.00022939], 
      [ 0.,   -0.2096513, 0.  ], 
      [ 0.00026388, 0.00026388, 0.00026388]]) 

for idx in range(3): 

    b = A[:, idx] 
    n1 = vectors(b) 
    print 'idx', idx, '\nb ', b, '\nn1 ', n1, '\n' 

Output: 

    idx 0 
    b [-0.00022939 0.   0.00026388] 
    n1 [array([ 0., -1., 0.])] 

    idx 1 
    b [-0.04265404 -0.2096513 0.00026388] 
    n1 [array([ 0.9799247 , -0.19936794, 0.  ])] 

    idx 2 
    b [ 0.00022939 0.   0.00026388] 
    n1 [array([ 0., 1., 0.])] 
+0

謝謝@DrBwts它的工作原理 –

+0

當我在我的代碼(矢量),函數您提到的循環僅爲第一列提供了n1和n2的值,而不是每列。因爲我需要爲每列計算n1和n2? –

+0

@ AL-Zetoun它工作正常,因爲我看到在我的回覆中做出的編輯 – DrBwts

0

你可以試試這個:

A=[[1,2,3],[4,5,6],[7,8,9]] 

def getColumn(m): 
    res=[] 
    for x in A: 
     res.append(x[m]) 
    return res 

def countSomething(x): 
    # counting code here 
    print x 

def looper(n): # n is the second dimension size 
    for x in xrange(0,n): 
     countSomething(getColumn(x)) 

looper(3) 
+0

謝謝@Jaroslaw –

+0

即時通訊我試圖使用你的代碼,通過函數向量代替函數countsomething在我的代碼上面,但它不起作用? 'def countSomething(b): b = b/np.sqrt(np.sum(b ** 2,axis = 0)) b = b/np.linalg.norm(b)\t z = np。 array([0.,0.1]) n1 = np.cross(z,b,axis = 0) n1 = n1/np.linalg.norm(n1)## normalize n n2 = np。 (b,n1,axis = 0) n2 = n2/np.linalg.norm(n2) return n1,n2' –

相關問題