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

问题描述

我有一个像这样的矩阵A

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

A仅具有唯一的行元素(零除外),并且每一行至少具有2个非零元素。

我想从B创建一个新的矩阵A,其中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,ColumnsOfSeconds );

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

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

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...