user2663126
user2663126

Reputation: 101

How to count number of 1's in the matrix

I have one matrix like-

A=[1 1 3 0 0;
   1 2 2 0 0;
   1 1 1 2 0;
   1 1 1 1 1];

From these "A" i need to count the number of 1"s of each row and after that i want to give the condition that after scanning each row of 'A' if the number of 1's >=3 then it take that. It means my final result will be

A= [1 1 1 2 0;
    1 1 1 1 1].

How can I do this. Matlab experts need your valuable suggestion.

Upvotes: 3

Views: 2269

Answers (2)

user2613077
user2613077

Reputation: 78

A=[1 1 3 0 0;...
   1 2 2 0 0;...
   1 1 1 2 0;...
   1 1 1 1 1]

accept = sum((A == 1)')
i = 1;k = 1;
while i <= length(A(:,1))
    if accept(k) < 3
       A(i,:) = [];
       i = i - 1;
    end
    i = i + 1;
    k = k + 1;
end
A

Upvotes: 0

NPE
NPE

Reputation: 500893

>> A(sum(A == 1, 2) >= 3, :)

ans =

     1     1     1     2     0
     1     1     1     1     1

Here, sum(A == 1, 2) counts the number of ones in each row, and A(... >= 3, :) selects the rows where the count is at least 3.

Upvotes: 5

Related Questions