从Matrix中提取正值和负值

时间:2013-09-12 09:50:12

标签: matlab matrix

我有像这样的3D矩阵

1   5648.00278672228    -46.43159546036
1   5650.38906894239    68.81787768047
1   5649.13081105839    -4867.55961979647
1   5650.53055771227    4868.95936645035
1   5647.95215053492    4866.38095927300
1   5650.21656586142    -2328.64537459950
1   5651.76371933598    7870.19252807406
1   5649.87288540620    -1168.30169414428

我希望将第3列的正值和负值提取到两个单独的2D矩阵(POS和NEG)中,其中第一列包含上述矩阵中行的索引,第二列包含值。

结果应该是

POS = 
2   68.81787768047
4   4868.95936645035
5   4866.38095927300
7   7870.19252807406

NEG =  
1   -46.43159546036
3   -4867.55961979647
6   -2328.64537459950
8   -1168.30169414428

3 个答案:

答案 0 :(得分:3)

您可以使用find功能和逻辑索引

POS = [find(A(:,3)>0) A(A(:,3)>0,3)]
NEG = [find(A(:,3)<=0) A(A(:,3)<=0,3)]

输入矩阵是A

A = [1   5648.00278672228    -46.43159546036
    1   5650.38906894239    68.81787768047
    1   5649.13081105839    -4867.55961979647
    1   5650.53055771227    4868.95936645035
    1   5647.95215053492    4866.38095927300
    1   5650.21656586142    -2328.64537459950
    1   5651.76371933598    7870.19252807406
    1   5649.87288540620    -1168.30169414428]

结果将是(format shortG

POS =

        2       68.818
        4         4869
        5       4866.4
        7       7870.2


NEG =

        1      -46.432
        3      -4867.6
        6      -2328.6
        8      -1168.3

由于@Dennis Jaheruddin和Khurram Majeed的评论,第二个发现被删除了。

答案 1 :(得分:3)

这是另一种方法

p = find(A(:,3)>0);
n = find(A(:,3)<0);

POS = [p A(p,3)]
NEG = [n A(n,3)]

请注意,这不包括零条目。如果您想在第一个向量中使用它们,例如使用>=而不是>

答案 2 :(得分:3)

这是另一种方式:

B = [(1:size(A,1)).' A(:,3)];
inds = B(:,2)>0;
POS = B( inds,:);
NEG = B(~inds,:);

这比Magla的find解决方案更快:

tic
for ii = 1:1e5
    B = [(1:size(A,1)).' A(:,3)];
    inds = B(:,2)>0;
    POS = B( inds,:);
    NEG = B(~inds,:);
end
toc

tic
for ii = 1:1e5
    POS = [find(A(:,3)>0) A(A(:,3)>0,3)];
    NEG = [find(A(:,3)<=0) A(A(:,3)<=0,3)];
end
toc

我糟糕的机器上的结果:

Elapsed time is 1.290744 seconds. % my new solution
Elapsed time is 2.004015 seconds. % Magla's solution w/ find()

这种差异部分是由于跳过find,否定逻辑索引而不是再次与<= 0进行比较,并重新使用索引而不是重新计算它们。

即使与Magla解决方案的更优化版本相比也是如此:

tic
for ii = 1:1e5
    inds = A(:,3)>0;
    POS = [find( inds) A( inds,3)];
    NEG = [find(~inds) A(~inds,3)];
end
toc

我们找到了

Elapsed time is 1.290744 seconds. % my new solution
Elapsed time is 1.476138 seconds. % Magla's solution w/ find()