How to compare a matrix and make decision on it?
1 view (last 30 days)
Show older comments
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 Comments
Walter Roberson
on 16 Jul 2020
Edited: Walter Roberson
on 16 Jul 2020
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);
Answers (1)
Walter Roberson
on 16 Jul 2020
n = nnz(YourMatrix) ;
if n <= 1
value = n;
else
error('more than one entry is 1, result undefined')
end
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!