Reputation: 21
I have a matrix(m*n). for every two rows, how I can find number of corresponding elements that are not zero. for example for following rows: r1=[1,3,0,4] , r2=[5,0,0,4] ,the answer is 2. because first and fourth elements in two rows are not zero. thanks
Upvotes: 2
Views: 67
Reputation: 112699
I'm assuming you want to consider each block ot two rows; that is, first row with second, third with fourth etc.
Reshape the m
×n
input matrix A
into an 2
×m/2
×n
3D array and then use all
and sum
along the appropriate dimensions:
result = sum(all(reshape(A, 2, [], size(A,2)), 1), 3);
As an example, for
A =
0 2 0 0 0
2 0 0 2 1
1 0 1 2 2
1 1 2 1 0
1 1 1 1 2
1 2 1 1 1
the result is
>> result = sum(all(reshape(A, 2, [], size(A,2)), 1), 3)
result =
0 3 5
Upvotes: 0
Reputation: 15837
You can use matrix multiplication:
L = logical(m); % convert the matrix to a logical matrix
result = L * L.'; % do matrix multiplication to compute number of corresponding elements
So the matrix element result(i,j)
represents the number of corresponding elements between row i
and row j
.
Upvotes: 3