Is there a vectorization way of returning the index of the last K nonzero elements of each row of a matrix?
For example, my matrix only contains 0 and 1 and the last column of each row is always 1. Then I want to find the index of the last K, where K>1, nonzero elements of each row. If a row only has M (less than K) nonzero elements, then the index for that row is just the index of the last M nonzero element. e.g.
A = [0 1 0 1;
1 1 0 1;
1 1 1 1;
0 0 0 1]
And my K = 2, then I expected to return a matrix such that
B = [0 1 0 1;
0 1 0 1;
0 0 1 1;
0 0 0 1]
Namely B
is originally a zero matrix with same shape as A
, then it copies each row of A
where the corresponding column starts from the index of the last K non-zero element of the row of A
(and if in one row of A
there is only M < K non-zero element, then it starts from the index of the last M non-zero element of that row of A
)
r
inA
you want to getfind(A(r,1:end-1)>0,1,'last')
, but without looping onr
? – EBHA(r,find(A(r,1:end-1)~=0,K,'last'))
, the whole part on theB
matrix is really not clear... – EBH