Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
768 views
in Technique[技术] by (71.8m points)

matlab - Find the first N non-zero elements in each row of a matrix

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]

I'd like the result to be:

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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];

Transpose and preallocate output 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

Index zeros

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

Bubble up the non-zeros

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

Select first N rows and transpose back

B(1:N,:)'

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...