How to compare a matrix and make decision on it?

1 回表示 (過去 30 日間)
joynob ahmed
joynob ahmed 2020 年 7 月 16 日
コメント済み: joynob ahmed 2020 年 7 月 17 日
I want to compare the component of a matrix so that if all the component is zero it will give value=0 and if any one component is 1 ,it will give value=1. All the matrix are not of same size always.For example it may be like this:
1×497 logical array
Columns 1 through 21
0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
Columns 22 through 42
0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Columns 43 through 63
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Columns 64 through 84
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Columns 85 through 105
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
Columns 106 through 126
0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1
Columns 127 through 147
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Columns 148 through 168
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Columns 169 through 189
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Columns 190 through 210
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Columns 211 through 231
0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Columns 232 through 252
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Columns 253 through 273
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Columns 274 through 294
0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0
Columns 295 through 315
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Columns 316 through 336
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Columns 337 through 357
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0
Columns 358 through 378
0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Columns 379 through 399
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Columns 400 through 420
0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0
Columns 421 through 441
0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0
Columns 442 through 462
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Columns 463 through 483
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Columns 484 through 497
0 0 0 0 0 0 0 0 0 0 0 0 0 0
  4 件のコメント
Walter Roberson
Walter Roberson 2020 年 7 月 16 日
編集済み: Walter Roberson 2020 年 7 月 16 日
This does not match the problem statement. The problem statement requires that value = 1 only if any one component of the array is 1, which means that if more than one component is 1 then the result should not be 1.
If "one or more components are 1" is acceptable then
value = any(arr);
joynob ahmed
joynob ahmed 2020 年 7 月 17 日
Actually I wanted to find out minimum one nonzero element. If more, there won't be any problem. So I guess it is right for me.

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

回答 (1 件)

Walter Roberson
Walter Roberson 2020 年 7 月 16 日
n = nnz(YourMatrix) ;
if n <= 1
value = n;
else
error('more than one entry is 1, result undefined')
end

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by