2012-02-24 229 views
1

我想選擇矩陣或向量的特定元素,可以說大於0.一種選擇是循環遍歷矩陣/向量的每個元素,但我想知道是否有更好的實現這一點的方式(如在R中,用哪種條件)。我的代碼如下所示:選擇矩陣元素(矩陣語言)

matrix. 
compute A={1,2,5,6,1,6,0,4,0,3,6,0,2,-3}. 
compute b=0. 

loop #i=1 to ncol(A). 
    do if (A(1,#i) >0). 
     compute b={b,a(1,#i)}. 
    end if. 
end loop. 

compute b=b(1,2:ncol(b)). 
print b. 

end matrix. 

回答

0

如果你有你想要的指數,你可以簡單地提供這些在一個單獨的子集向量。

matrix. 
compute A={1,2,5,6,1,6,0,4,0,3,6,0,2,-3}. 
compute take = {1,2,4}. 
print A(take). 
end matrix. 

它在打印語句上產生1 2 6。現在,抓住指數有點煩人。一種方法是在否定會議條件時使用GRADE,它提供了一個訂單來獲取所需的索引。然後只選擇您知道符合條件的索引總數。

matrix. 
compute A={1,2,5,6,1,6,0,4,0,3,6,0,2,-3}. 

*make sequential index and vector with selection. 
compute take = {1:NCOL(A)}. 
compute sel = A > 0. 

*reording the indices so the selected columns are first. 
compute take(GRADE(-1*sel)) = take. 

*only taking the indices that meet the selection. 
compute take = take(1:RSUM(sel)). 

*results. 
print A. 
print A(take). 
end matrix. 

這可以捲成一個宏,使這容易。這裏是一個可以在這裏工作的例子。

DEFINE !SelCol (Data = !TOKENS(1) 
       /Condition = !TOKENS(1) 
       /Result = !TOKENS(1)) 
COMPUTE XKeepX = !UNQUOTE(!Condition). 
COMPUTE XIndX = {1:NCOL(!Data)}. 
COMPUTE XIndX(GRADE(XKeepX*-1)) = XIndX. 
COMPUTE XIndX = XIndX(1:RSUM(XKeepX)). 
COMPUTE !Result = !Data(1:NROW(!Data),XIndX). 
RELEASE XKeepX. 
RELEASE XIndX. 
!ENDDEFINE. 

MATRIX. 
COMPUTE A={1,2,5,6,1,6,0,4,0,3,6,0,2,-3}. 
!SelCol Data=A Condition='A>0' Result=ASel. 
PRINT ASel. 
END MATRIX. 

該方法很容易適用於選擇矩陣的特定行。

DEFINE !SelRow (Data = !TOKENS(1) 
       /Condition = !TOKENS(1) 
       /Result = !TOKENS(1)) 
COMPUTE XKeepX = !UNQUOTE(!Condition). 
COMPUTE XIndX = {1:NROW(!Data)}. 
COMPUTE XIndX(GRADE(XKeepX*-1)) = XIndX. 
COMPUTE XIndX = XIndX(1:CSUM(XKeepX)). 
COMPUTE !Result = !Data(XIndX,1:NCOL(!Data)). 
RELEASE XKeepX. 
RELEASE XIndX. 
!ENDDEFINE. 

這應該是相當快的。大部分時間將用於條件語句並提取數據。即使對於大量的行或列,排名索引也應該很小。