0

I have a 6x6 double matrix A:

 1   1   2  -1  -2   2

-1  -3   1   1   2   1

 3   5   1  -1  -3   3

 4  -5   2   2   1  -3

-4   1   3   3  -2   3

 2   3  -3  -4   2  -3

How do I find the number of positive values from this matrix using MATLAB?

IKavanagh
  • 6,089
  • 11
  • 42
  • 47
mrstudentchan
  • 103
  • 1
  • 4

5 Answers5

10

You can use

sum(A(:) >= 0)
ans = 23

Out of curiosity a quick performance check:

A = randn(10000);

tic 
sum(A(:) >= 0);
toc

tic 
nnz(sign(A)+1);
toc

tic 
size(find(A>=0),1);
toc

tic 
length(A(A>=0));
toc

Elapsed time is 0.147514 seconds.
Elapsed time is 0.769115 seconds.
Elapsed time is 1.107935 seconds.
Elapsed time is 0.820353 seconds.
Tobias
  • 4,034
  • 1
  • 28
  • 35
  • 1
    a veeery simple way of benchmarking. But anyway: I used [this one](http://stackoverflow.com/a/21121323/2605073) and your solution is still the fastest, especially for bigger matrices. – Robert Seifert Jan 15 '14 at 10:45
  • 2
    By the way, 0 is not positive. That's why I used `>` instead of `>=`... – António Almeida Jan 15 '14 at 10:48
2

My suggestion:

nnz(sqrt(A)+sqrt(A)'.')
ans =  23

This is not the fastest solution, but it's the only one that illustrates the difference between ' and .'.

Stewie Griffin
  • 14,889
  • 11
  • 39
  • 70
1

Use find:

> count = size(find(A>=0),1)
count =  23
Paul R
  • 208,748
  • 37
  • 389
  • 560
1
x = [
  1  1  2 -1 -2  2 ;
 -1 -3  1  1  2  1 ;
  3  5  1 -1 -3  3 ;
  4 -5  2  2  1 -3 ;
 -4  1  3  3 -2  3 ;
  2  3 -3 -4  2 -3 ]

length( x(x>0) )

ans = 23

António Almeida
  • 9,620
  • 8
  • 59
  • 66
1

a little more unconventional:

nnz(sign(A)+1)

but slow for larger matrices, I have to admit.

Robert Seifert
  • 25,078
  • 11
  • 68
  • 113