Converting a list of Mathematica values ​​to a logical list

First of all, sorry for the confusing name.

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

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

That is, only the indices from the first list will be True , the rest will be False .

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

Thanks for your help.


EDIT: to show that I was trying to do something before I asked, here is my progress:

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

Unfortunately, it does not work with {1,4,9} -> True , but it will work with {1 -> True, 4 -> True, 9 -> True} . But I don’t know how to get to this ...


EDIT 2: received.

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

I will be glad to see your decisions anyway! This one seems like an ugly hack to me ... :)

+6
source share
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 solution above written as a convenience function:

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

Application:

 convertIndices@ {1, 4, 9} Out[2]= {True, False, False, True, False, False, False, False, True} 
+13
source

I would use SparseArray for this operation. In my opinion, this is very easy to understand, and it is also effective, especially if the low percentage of True indexes.

 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 need to convert the output to a regular array, but most operations will not require this.


Also, sacrificing practicality for patience:

 #==1 & /@ SparseArray[List /@ true -> 1] 
+8
source

Actually, I would use Yoda 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 of skipping the initialization step of Yoda ConstantArray .

+2
source

Source: https://habr.com/ru/post/900857/


All Articles