簡體   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