2
$\begingroup$

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:

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

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.

Thanks.

$\endgroup$

2 Answers 2

7
$\begingroup$

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 :).

$\endgroup$
4
  • 1
    $\begingroup$ You don't need Map for that: ReplacePart[M, L -> s] works as well $\endgroup$
    – Carlo
    Aug 5, 2014 at 18:06
  • $\begingroup$ @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. $\endgroup$ Aug 5, 2014 at 18:09
  • 1
    $\begingroup$ There is an old syntax for ReplacePart that saves a couple of keystrokes: ReplacePart[M, s, #] & /@ L $\endgroup$
    – Mr.Wizard
    Aug 5, 2014 at 18:17
  • $\begingroup$ oh I see, sorry I misread the question. $\endgroup$
    – Carlo
    Aug 5, 2014 at 18:55
0
$\begingroup$

You can also use MapAt, Part assignment and MapIndexed as follows:

m1 = MapAt[s &, M, #] & /@ L; 
m2 = Module[{m = M}, m[[## & @@ #]] = s; m] & /@ L;
m3 = Function[x, MapIndexed[If[#2 == x, s, #] &, M, {2}]] /@ L ;
m4 = MapIndexed[Function[{x, y}, If[y == #, s, x]], M, {2}] & /@ L ;

Equal[m1, m2, m3, m4]

True

TeXForm[MatrixForm[m1[[1]]]]

$\left( \begin{array}{ccc} a(1,1) & s & a(1,3) \\ a(2,1) & a(2,2) & a(2,3) \\ a(3,1) & a(3,2) & a(3,3) \\ \end{array} \right)$,

TeXForm[MatrixForm[m1[[2]]]]

$\left( \begin{array}{ccc} a(1,1) & a(1,2) & a(1,3) \\ s & a(2,2) & a(2,3) \\ a(3,1) & a(3,2) & a(3,3) \\ \end{array} \right)$,

TeXForm[MatrixForm[m1[[3]]]] 

$\left( \begin{array}{ccc} a(1,1) & a(1,2) & a(1,3) \\ a(2,1) & s & a(2,3) \\ a(3,1) & a(3,2) & a(3,3) \\ \end{array} \right)$

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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