0

So I have, say, 5 different vectors or matrices. I basically want to make an If statement on whether any one of these matrices contains a specific element (e.g. 2), and then display some value (e.g. 8) if any of these matrices does contain this element. It doesn't matter if four of these matrices don't contain the element, if one does then I will display 8.

Thanks for the help

Name Name
  • 55
  • 1
  • 2
  • possible duplicate of [MATLAB function for 'does matrix contain value X?' (ala php's in\_array())](http://stackoverflow.com/questions/1913670/matlab-function-for-does-matrix-contain-value-x-ala-phps-in-array) – Eitan T Sep 16 '13 at 09:23
  • Not neccesarily a duplicate as this one asks for multiple matrices simultaneously. – Dennis Jaheruddin Sep 16 '13 at 13:10

2 Answers2

2

Assuming your matrices are A,B,C,D and E. Here is a way to check if any of them contains 2.

any(A(:) == 2) || any(B(:)== 2) || any(C(:)== 2) || any(D(:)== 2) || any(E(:) == 2)

Note the use of || instead of |, this means that if one matrix is found to contain a 2, it will no longer have to check the other matrices.

An alternate, more compact way to do this (probably less efficient though):

any([A(:); B(:); C(:);D(:);E(:)] == 2)

From here it should be trivial to display 8 if the statement is true.

Dennis Jaheruddin
  • 21,208
  • 8
  • 66
  • 122
0

consider having 5 different matrices named a1, a2, ..., a5

if(numel(find(a1==2))|(numel(find(a2==2)))|(numel(find(a3==2)))|(numel(find(a4==2)))|  (numel(find(a5==2))))
display(8)
end

you can use any if number of repetitions is not important:

if(any(a1(:)==2)|any(a2(:)==2)|any(a3(:)==2)|any(a4(:)==2)|any(a5(:)==2))
display(8)
end
Roozi
  • 683
  • 6
  • 12
  • 2
    Should get the job done, but especially if the last few matrices are large you will want to avoid evaluating them unless it is neccesary. – Dennis Jaheruddin Sep 16 '13 at 13:14