繁体   English   中英

从矩阵的每一行中获取前 2 个非零元素

[英]Get the first 2 non-zero elements from every row of matrix

我有一个这样的矩阵A

A = [ 1 0 2 4; 2 3 1 0; 0 0 3 4 ]

A除了零之外只有唯一的行元素,并且每行至少有 2 个非零元素。

我想从A创建一个新矩阵B ,其中B中的每一行都包含A中相应行的前两个非零元素。

B = [ 1 2 ; 2 3 ; 3 4 ]

循环很容易,但我需要矢量化解决方案。

这是一种矢量化方法:

A = [1 0 2 4; 2 3 1 0; 0 0 3 4]; % example input
N = 2; % number of wanted nonzeros per row
[~, ind] = sort(~A, 2); % sort each row of A by the logical negation of its values.
% Get the indices of the sorting
ind = ind(:, 1:N); % keep first N columns
B = A((1:size(A,1)).' + (ind-1)*size(A,1)); % generate linear index and use into A

这是另一种矢量化方法。

A_bool = A > 0;   A_size = size(A);   A_rows = A_size(1);
A_boolsum = cumsum( A_bool, 2 ) .* A_bool;   % for each row, and at each column,
                                             % count how many nonzero instances
                                             % have occurred up to that column
                                             % (inclusive), and then 'zero' back
                                             % all original zero locations.

[~, ColumnsOfFirsts  ] = max( A_boolsum == 1, [], 2 );
[~, ColumnsOfSeconds ] = max( A_boolsum == 2, [], 2 );

LinearIndicesOfFirsts  = sub2ind( A_size, [1 : A_rows].', ColumnsOfFirsts  );
LinearIndicesOfSeconds = sub2ind( A_size, [1 : A_rows].', ColumnsOfSeconds );

Firsts  = A(LinearIndicesOfFirsts );
Seconds = A(LinearIndicesOfSeconds);

Result = horzcat( Firsts, Seconds )
% Result = 
%    1   2
%    2   3
%    3   4

PS。 Matlab / 八度通用子集兼容代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM