Kelly
Kelly

Reputation: 87

How to initiate IF statement if variable is only contained in matrix (matlab)

I am looking to achieve something that seems fairly simple, just not sure how to implement ORs in an IF statement:

A = [4 6 7; 3 4 7; 8 7 1]
C = 6
if C is in first row of A 
(i.e. if row 1 contains 6, basically -- IF C = 4 or C=6 or C=7)    
    (then do this)
end

Any suggestions?

Upvotes: 0

Views: 117

Answers (2)

Swagatika
Swagatika

Reputation: 885

   A = [4 6 7; 3 4 7; 8 7 1];
   C = 6;

   rowNum = 1;

   if (sum(A(rowNum,:) == C) ~= 0)
      do something
   end

Upvotes: 0

jedwards
jedwards

Reputation: 30200

So

A(1,:) == C

is a start. In your case, it will return a 3 element boolean array where

ans(1) = 1 if A(1,1) == C, 0 otherwise
ans(2) = 1 if A(1,2) == C, 0 otherwise
ans(3) = 1 if A(1,3) == C, 0 otherwise

From there, you could do something like

if( sum(A(1,:) == C) )
# or
if( length(find(A(1,:) == C)) )

would work.

Upvotes: 2

Related Questions