2

我有这样的 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)中,其中第 1 列包含上述矩阵中行的索引,第 2 列包含该值。

结果应该看起来像

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
4

3 回答 3

3

这是另一种方法

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

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

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

于 2013-09-12T10:08:34.480 回答
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()
于 2013-09-12T10:43:13.633 回答
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 的评论,第二个发现被删除。

于 2013-09-12T10:00:18.543 回答