bzak
bzak

Reputation: 563

Calculate the number of columns in a matrix satisfying some conditions

M = [1022  3001  4451 1022 1022  3001 1022;
      112    45    10  112  112    45  11;
      500    11    55  500  500    11  88;
        2     5     3   99   71    22   2]  



A = M(1:3,:)



B = unique(A','rows')' = [1022        1022        3001        4451
                            11         112          45          10
                            88         500          11          55]

I want for each column B(:,k), k=1:size(B,2), to find the number of column in M that satisfy M(4,j)>50. j is a possible index of column vector containing B(:,k) in M.

C = [1022        1022        3001        4451
       11         112          45          10
       88         500          11          55
        0           2           0           0]    

C(4,:) is the desired result.

Upvotes: 0

Views: 49

Answers (1)

Divakar
Divakar

Reputation: 221514

This should work for you -

threshold = 50;

%// Find unique columns for first three rows of M
[unqM,~,IDs] = unique(M(1:3,:).','rows')  %//'

%// Find the fourth row elements from M that satisfy the threshold
matches = M(end,:)>threshold

%// Get the counts of the unique columns satisfying threshold criteria
out1 = sum(bsxfun(@times,bsxfun(@eq,IDs,1:max(IDs)),matches'),1) %//'
%// OR with HISTC: out1 = histc(IDs.*matches',1:max(IDs)).'

%// Concatenate with the unique columns for the final output
out = [unqM.' ; out1]

Upvotes: 1

Related Questions