0
$\begingroup$

If I have a vector {1,2,3}, I want to write an If statement, where if one of the positions is "1", it will perform a certain command.

test = {1, 2, 3}
# == 1 & /@ test 
If[# == 1 & /@ test == True, Print["Yes"], Print["no"]]

I get this as the output:

If[{True, False, False} == True, Print["Yes"], Print["no"]]

What am I doing wrong? I am new to Mathematica.

$\endgroup$
  • 1
    $\begingroup$ Use MemberQ to test if an element is in the list. $\endgroup$ – Szabolcs Apr 29 '14 at 18:31
  • 1
    $\begingroup$ You should study the answers to this question Map a function across a list conditionally. In fact this is a duplicate. $\endgroup$ – Artes Apr 29 '14 at 18:34
0
$\begingroup$

There are a number of different solutions. Here are a few:

test = {1, 2, 3}
# == 1 & /@ test

If[Or @@ Thread[# == 1 & /@ test == True], Print["Yes"], Print["no"]]
If[Or @@ (# == 1 & /@ test), Print["Yes"], Print["no"]]
If[MemberQ[test, 1], Print["Yes"], Print["No"]]

In my opinion these are in increasing order of clarity and good practice.

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.