2
$\begingroup$

I have this list:

{{5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24}, {25, 26, 27, 28, 29}}

For learning purposes I try to replace one number (random) in each sublist with "a". I try to do it by using a pure function, but I get an error when using this code:

mylist = Range[5 #, 5 # + 4] & /@ Range[5]
i = Random[Integer, {1, 5}]
mylist[[#, i]] & /@ Range[1, 5] = a

Why do I get an error and what should I do instead?

$\endgroup$
2
$\begingroup$
list = Partition[Range[5, 29], 5];

SeedRandom[1]

(list[[#, RandomInteger[{1, 5}]]] = a) & /@ Range@Length@list

or

ReplacePart[list, i_ :> {list[[i, RandomInteger[{1, 5}]]] = a}]

or

MapThread[(list[[##]] = a) &, {Range@5, RandomInteger[{1, 5}, 5]}]

all give

list // MatrixForm

enter image description here

If you want to replace at the same position it would simply be

list[[All, RandomInteger[{1, 5}]]] = a;

list // MatrixForm

enter image description here

$\endgroup$
5
$\begingroup$

The problem is that you are trying to Set the entirety of mylist[[#, i]] & /@ Range[1, 5] to a. This expression really looks like

Map[mylist[[#, i]] &, Range[1, 5]] = a

which means you are trying to associate a definition with Map, which is a protected function, just like

f[something] = a

associates a definition with f. Evaluating the expression first doesn't work either, i.e.

Evaluate[mylist[[#, i]] & /@ Range[1, 5]] = a

because the left-hand side evaluates to {a, a, a, a, a}, which is the same as List[a, a, a, a, a], and then you are trying to associate a definition with List, which is protected as well.

Here's how you would make it work using your idea: (mylist[[#, i]] = a) & /@ Range[1, 5].

Here's the most straight-forward way:

mylist[[All, i]] = a
$\endgroup$
4
$\begingroup$

A better explanation as why was given by march.

To fix your code you can simply reorder your last line:

(mylist[[#,i]]=a)&/@Range[1,5]

But it is simpler. You can use multiple targets in one reference, just do:

mylist[[Range[1, 5], i]] = a

BTW: Random[Integer,...] is deprecated!

Use RandomInteger instead!

$\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.