I have the following xy list:

list = {{19, 21991.4}, {63, 5801.71}, {71, 5714.21}, {99, 2021.72}, {135,
850.353}, {165, 1897.}, {220, 2117.53}, {251, 2444.39}, {274,
25136.6}}


I am just interested in the x positions, so I do the following:

x = First[list[[#]]] & /@ Range[Length[list]]


which gets me: {19, 63, 71, 99, 135, 165, 220, 251, 274}

Now I would like to create the following lists:

1. A list where there are zeros everywhere expect for the positions given at x, so something like this: 0,0,0,0,...1 (at position 19), 0,0,... 1 (at position 63)...

2. A list where I have 1,1,1,1, until position 19, then 2,2,2,2 until position 63 then 3,3,3,3 until position 71 etc.

How could I achieve that ?

• You can also use x=First/@list Aug 20, 2018 at 6:09

First of all, you should use Part or its shorthand [[...]] to retrieve list elements, like so:

xvalues = list[[All, 1]]


{19, 63, 71, 99, 135, 165, 220, 251, 274}

As for list (1), this is often done using SparseArray.

sa = SparseArray[xvalues -> ConstantArray[1, Length[xvalues]], 300];
Normal[sa]


Normal converts the sparse array to a normal list. Any elements that don't have values will be turned into zeros, which is what we want. 300 is the length of the list that you create when you apply Normal to the sparse array.

For list (2), we have to apply Accumulate to this list and also add 1 since it starts counting at 1. This can be done using the sparse array directly or by converting it to a normal list first, it doesn't matter.

Accumulate[sa] + 1

• Thanks a lot for the answer. What does the " 300" represent in the sparse Array ? Aug 19, 2018 at 22:46
• @james There is a sentence about this in the answer, but I added in an update so you may have to refresh the page to see it. Aug 19, 2018 at 22:49

Here you go:

First Question:

firstList =
Table[If[MemberQ[list, i], 1, 0], {i, 1,
Length[list]}]


Second Question:

m = 1
secondList =  firstList =
Table[If[MemberQ[list, i], m+1, m], {i, 1,
Length[list]}]

• Your list needs to go up to Max[List[[;;1]] rather than length Aug 19, 2018 at 23:42

You can create the desired vector using Part by indexing into a vector of all zeros.

xvals = list[[All, 1]];
zeroOne = ConstantArray[0, Max[xvals]];
zeroOne[[xvals]] = 1


So the vector zeroOne now contains ones at just the xvals and zeros everywhere else.