Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a sublist from Tuples[{1, 2, 3}, 2], say for example L={{1,2},{2,1},{2,2}}, and a 3 x 3 matrix M.

My goal is to create a new list of matrices that has the same length as L and these matrices are the same as M except in the position indexed by elements of L, that is replaced by some constant number s.

As I am used to Matlab, I did in an iterative way:

While[j <= Length[L], 
  State = M;
  State[[L[[j, 1]], L[[j, 2]]]] = s;
  If[MemberQ[NewList, State] == False, AppendTo[NewList, State]];

but it would have be nicer to use the function Map I guess. So I'm looking for an elegant synthax since a little while.


share|improve this question
up vote 3 down vote accepted

You are completely right: using Map is much nicer than an iterative approach. Here's one way you might do it:

ReplacePart[M, # -> s]& /@ L

Here /@ is a short-hand input form of Map, and the #& combination is what's known as a pure function. Welcome to Mathematica :).

share|improve this answer
You don't need Map for that: ReplacePart[M, L -> s] works as well – Carlo Aug 5 '14 at 18:06
@Carlo No, that gives only one matrix of which all entries indexed by L are replaced. The OP wants a list of matrices of which each has only one entry replaced. – Teake Nutma Aug 5 '14 at 18:09
There is an old syntax for ReplacePart that saves a couple of keystrokes: ReplacePart[M, s, #] & /@ L – Mr.Wizard Aug 5 '14 at 18:17
oh I see, sorry I misread the question. – Carlo Aug 5 '14 at 18:55

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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