2
$\begingroup$

Consider some list

list={1.2,1.6,1.8,1.9,2,2.22,3.04,1000};

I would like to check whether some parameter x belongs to the values of the list, and if it does, then return parameter^2, while if it does not, then return 0. Could you please tell me how to do this?

$\endgroup$
1
  • 4
    $\begingroup$ f = Boole@MemberQ[list, #]*#^2 & $\endgroup$
    – cvgmt
    Jan 13 at 15:48
6
$\begingroup$

There are few way. One could be to use MemberQ with an If

list = {1.2, 1.6, 1.8, 1.9, 2, 2.22, 3.04, 1000};
x = 1.6;
If[MemberQ[list, x], x^2, 0]

Mathematica graphics

$\endgroup$
4
$\begingroup$

Try this:

check[x_] := If[MemberQ[lst, x], x^2, 0]

Let us test it:

lst = {1.2, 1.6, 1.8, 1.9, 2, 2.22, 3.04, 1000};

check[1.9]

(*  3.61 *)

check[1.8]

(*  3.24  *)

check[1.7]

(*  0 *)

Done. Have fun!

$\endgroup$
2
$\begingroup$
f = #^2 Unitize@Length@Cases[alist, #] &

For testing:

tList = RandomReal[{-10, 10}, {10}]~Join~alist~Join~
  RandomInteger[{-10, 10}, {10}]

f /@ tList

{0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.44, 2.56, 3.24, 3.61, 4, \
4.9284, 9.2416, 1000000, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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