在矩阵的每一行中找到前N个非零元素 [英] Find the first N non-zero elements in each row of a matrix
问题描述
我在MATLAB中有一个零的矩阵,我想在每一行中得到另一个带有第一个N
非零元素的矩阵.例如,假设N = 3
,矩阵为
I have a matrix in MATLAB with zeroes and I would like to get another matrix with the first N
non-zero elements in each row. Let's say for example N = 3
, and the matrix is
A = [ 0 0 2 0 6 7 9;
3 2 4 7 0 0 6;
0 1 0 3 4 8 6;
1 2 0 0 0 1 3]
我希望结果是:
B = [2 6 7;
3 2 4;
1 3 4;
1 2 1]
我有一个巨大的矩阵,所以我想不加循环地进行操作,您能帮我吗?非常感谢!
I have a huge matrix so I would like to do it without a loop, could you please help me? Thanks a lot!
推荐答案
因为MATLAB根据存储矩阵按列优先顺序,我首先转置A
,将非零气泡冒出,然后选择前N
行,然后转置回去:
Since MATLAB stores a matrix according to column-major order, I first transpose A
, bubble up the non-zeros, and pick the first N
lines, and transpose back:
N = 3;
A = [ 0 0 2 0 6 7 9;
3 2 4 7 0 0 6;
0 1 0 3 4 8 6;
1 2 0 0 0 1 3];
转置并预分配输出B
At = A';
B = zeros(size(At));
At =
0 3 0 1
0 2 1 2
2 4 0 0
0 7 3 0
6 0 4 0
7 0 8 1
9 6 6 3
索引零
idx = At == 0;
idx =
1 0 1 0
1 0 0 0
0 0 1 1
1 0 0 1
0 1 0 1
0 1 0 0
0 0 0 0
冒泡非零
B(~sort(idx)) = At(~idx);
B =
2 3 1 1
6 2 3 2
7 4 4 1
9 7 8 3
0 6 6 0
0 0 0 0
0 0 0 0
选择前N
行并向后转置
B(1:N,:)'
您可以按行优先的顺序进行冒泡,但是您需要使用find检索行和列下标,并在那里进行一些排序和选择.它变得更加乏味且可读性较低.
You can do the bubbling in row-major order, but you would need to retrieve the row and column subscripts with find, and do some sorting and picking there. It becomes more tedious and less readable.
这篇关于在矩阵的每一行中找到前N个非零元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!