选择矩阵元素(矩阵语言)

时间:2012-02-24 16:53:38

标签: spss

我想选择矩阵或向量的特定元素,让我们说大于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.

1 个答案:

答案 0 :(得分: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.

在print语句中生成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.

这应该很快。大部分时间将花在条件语句上并提取数据。即使对于非常多的行或列,索引的排名也应该非常简单。