How to find out if a logical array is all zeros?

244 ビュー (過去 30 日間)
MKM
MKM 2022 年 2 月 3 日
コメント済み: MKM 2022 年 2 月 4 日
I have a logical array that is 100x1 logical. sometimes it contains a mix of numbers and sometimes it contains all 0s.
How would i go about making an if statement that checks to see if all 100x1 is 0s and if all 0s = do something
I thought i was correct in using any command but im not sure that works correctly for me..
Thanks!

採用された回答

John D'Errico
John D'Errico 2022 年 2 月 3 日
編集済み: John D'Errico 2022 年 2 月 3 日
any does work, with a slight tweak. But you could also use all, or sum, or nnz, or even find. There are certainly many ways.
if ~any(X)
...
end
if all(~X)
...
end
if sum(x) == 0
...
end
if numel(find(x)) == 0
...
end
if nnz(x) == 0
...
end
Any of those tools would suffice.

その他の回答 (4 件)

Turlough Hughes
Turlough Hughes 2022 年 2 月 3 日
One way:
~any(x)

William Rose
William Rose 2022 年 2 月 3 日
If A is a vector,
sum(abs(A))
will be zero, or not, of all the elements are zero, or not.
If A is a 2D array, do
sum(sum(abs(A)))

David Hill
David Hill 2022 年 2 月 3 日
if all(~yourArray)

Steven Lord
Steven Lord 2022 年 2 月 3 日
For a vector, all with one input will work.
x = ones(10, 1);
all(x > 0) % true
ans = logical
1
For a non-vector array you probably want to specify a dimension. In recent releases, you can specify a vector of dimensions on which to operate or you can specify 'all' as the dimension to operate on all the dimensions no matter how many there are.
x = ones(10, 10);
all(x > 0) % Only operate on dimension 1
ans = 1×10 logical array
1 1 1 1 1 1 1 1 1 1
all(x > 0, 'all') % Operate on dimensions 1 and 2
ans = logical
1
x = ones(10, 10, 10);
all(x > 0, [1 3]) % Operate on dimensions 1 and 3
ans = 1×10 logical array
1 1 1 1 1 1 1 1 1 1
all(x > 0, 'all') % Operate on dimensions 1, 2, and 3
ans = logical
1
  1 件のコメント
MKM
MKM 2022 年 2 月 4 日
This is great! Thanks for taking the time to help me with this.

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

カテゴリ

Help Center および File ExchangeDiscrete Data Plots についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by