checking if every component of a vector is nonnegative

25 ビュー (過去 30 日間)
Del
Del 2012 年 12 月 21 日
コメント済み: Walter Roberson 2022 年 3 月 2 日
What is the easiest way to check whether a vector a is >= 0?
I know you could type
a>=0 and get a vector of ones if that's true, but I am looking for something that will give me only one 1 as an answer.
For instance,
a=[2 5 3 6]; >> a>=0
ans =
1 1 1 1
But I am looking for something that will give me just
ans=
1 (as the answer)
any idea?
  2 件のコメント
Ganindu
Ganindu 2014 年 9 月 11 日
use, all(a>=0)
Image Analyst
Image Analyst 2014 年 9 月 11 日
That is the same answer that Walter gave below almost 2 years ago.

サインインしてコメントする。

回答 (2 件)

Walter Roberson
Walter Roberson 2012 年 12 月 21 日
all(a >= 0)
However, what if there are NaN in the array? NaN is "nonnegative" (in some definitions) but also not >= 0 .
  2 件のコメント
Suraj Parasuram
Suraj Parasuram 2022 年 3 月 2 日
@Walter Roberson Is this available in Simulink? How can I implement this in Simulink?
Walter Roberson
Walter Roberson 2022 年 3 月 2 日
minmax block to take the min() of the input.
if-else testing whether the min was >= 0
In some contexts you would instead take sign() https://www.mathworks.com/help/simulink/slref/sign.html .
If you add 2 to the sign() then you can use that as the index into a vector of length 3 -- "some entry less than 0" "smallest entry was 0" "smallest entry was greater than 0"

サインインしてコメントする。


Shaun VanWeelden
Shaun VanWeelden 2012 年 12 月 21 日
An extremely intuitive answer would just be return the minimum of the logic matrix that results from your inequality. It will only be 1 if every value turns out to be a 1.
min(A>=0) and by the way it returns a zero for NaN
  2 件のコメント
Teja Muppirala
Teja Muppirala 2012 年 12 月 21 日
The difference between using ALL and MIN, is that when you use ALL it will stop searching through the vector once it finds even a single location where the condition is not true. So it will work a slight bit faster than MIN in this case.
For example:
% Takes 1 sec. on my PC
R = zeros(1,1e8); R(1) = -1;
tic; for n = 1:10, all(R >= 0); end; toc;
% Takes 2 sec. on my PC
R = zeros(1,1e8); R(1) = -1;
tic; for n = 1:10, min(R >= 0); end; toc;
Walter Roberson
Walter Roberson 2012 年 12 月 21 日
I don't think it has ever been conclusively demonstrated that all() stops at the first false, or whether it is parallelized for "big enough" matrices. My recollection is that someone created a mex version that was found to be faster than all() in ways that you would expect if all() tested all (or most) locations -- e.g., much faster for the mex version if the condition was false early.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by