Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Mathematica list of values into boolean list

First of all, sorry for the confused title.

What I want to do is to convert {1, 4, 9} to:

{True, False, False, True, False, False, False, False, True}

That is, only the indexes from the first list will have value True, the rest will be False.

I sense there is some really simple solution, but I am quite new to both Mathematica and functional programming. I could do it iteratively, in a loop, but there has to be something that works with the list as a whole. Right? :)

Thanks for your help.


EDIT: to show that I tried to do something before I asked, here's my progress so far:

first={1,4,9}
ReplacePart[Table[False, {x, Max[first]}], {1} -> True]
(* gives {True, False, False, False, False, False, False, False, False} *)

Unfortunately, it doesn't work with {1,4,9} -> True, but would work with {1 -> True, 4 -> True, 9 -> True}. But I don't know how to get to that...


EDIT 2: got it.

ReplacePart[Table[False, {x, Max[first]}], Table[x -> True, {x, first}]]

I'd still love to see your solutions! This one seems like an ugly hack to me ... :)

like image 865
Martin Janiczek Avatar asked Nov 05 '11 21:11

Martin Janiczek


3 Answers

Here's a simple approach:

first = {1, 4, 9};
list = ConstantArray[False, Max@first];
list[[first]] = True;

list
Out[1]= {True, False, False, True, False, False, False, False, True}

Here's the above solution written as a convenient function:

Clear[convertIndices]
convertIndices[index_List] := 
 Module[{list = ConstantArray[False, Max@index]}, 
  list[[index]] = True; list]

Usage:

convertIndices@{1, 4, 9}
Out[2]= {True, False, False, True, False, False, False, False, True}
like image 117
abcd Avatar answered Oct 21 '22 03:10

abcd


I would use SparseArray for this operation. In my opinion it is very easy to understand, and it is also efficient, especially when a low percentage of indices are True.

true = {1, 4, 9};
SparseArray[(List /@ true) -> True, Automatic, False]

Alternatively with Transpose (which looks better when pasted into Mathematica):

SparseArray[{true}\[Transpose] -> True, Automatic, False]

You can use Normal if you must convert the output to a normal array, but most operations will not require that.


Also, sacrificing practicality for terseness:

#==1 & /@ SparseArray[List /@ true -> 1]
like image 22
Mr.Wizard Avatar answered Oct 21 '22 05:10

Mr.Wizard


Actually, I would have used Yoda's answer myself, but here's an alternative:

first = {1, 4, 9};
MemberQ[first, #] & /@ Range[Max[first]]

(* ===> {True, False, False, True, False, False, False, False, True}*)

Or this one:

Or @@@ Outer[Equal, Range[Max[first]], first]


(* ===> {True, False, False, True, False, False, False, False, True}*)

Both have the advantage that they skip Yoda's ConstantArray initialization step.

like image 30
Sjoerd C. de Vries Avatar answered Oct 21 '22 03:10

Sjoerd C. de Vries