如何解决从矩阵的每一行获取前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通用子集兼容代码。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。