使用MATLAB从Matrix中查找正值的数量

mrs*_*han 0 matlab matrix

我有一个6x6双矩阵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
Run Code Online (Sandbox Code Playgroud)

如何使用MATLAB从该矩阵中找到正值的数量?

Tob*_*old 9

您可以使用

sum(A(:) >= 0)
ans = 23
Run Code Online (Sandbox Code Playgroud)

出于好奇,快速进行性能检查:

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.
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句,0不是正面的.这就是为什么我用`>`而不是`> =`... (2认同)