Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I have a list of sequences of x's and y's. I want to switch the last position to the "opposite" symbol - if x, replace with y; if y, replace with x.

It is in the following format:

{{{x,x,x,x,x,y,y},{x,x,x,x,y,y,x},{x,x,x,y,y,x,x},{x,x,y,y,x,x,x},
  {x,y,y,x,x,x,x},{y,x,x,x,x,x,y},{y,y,x,x,x,x,x}},
 {{x,x,x,x,y,x,y},{x,x,x,y,x,y,x},{x,x,y,x,y,x,x},{x,y,x,x,x,x,y},
  {x,y,x,y,x,x,x},{y,x,x,x,x,y,x},{y,x,y,x,x,x,x}},
 {{x,x,x,y,x,x,y},{x,x,y,x,x,x,y},{x,x,y,x,x,y,x},{x,y,x,x,x,y,x},
  {x,y,x,x,y,x,x},{y,x,x,x,y,x,x},{y,x,x,y,x,x,x}}}

So for each monomial with length 7, I want to replace the last part with the opposite. Does anyone know an easy way to program it with Mathematica? I will be doing this for lists of different length: 7,11,13,15,17.

share|improve this question
    
@Kuba wicked :D –  Yves Klett Jun 11 at 18:34
    
@YvesKlett mine too, I've added A at the end to the result is clear now. Still not sure about my interpretation :) –  Kuba Jun 11 at 18:40
    
@Kuba d´oh! Well, go on and answer, then! –  Yves Klett Jun 11 at 18:40
    
@Öskå splitting hairs ;-) –  Yves Klett Jun 11 at 18:41

2 Answers 2

up vote 4 down vote accepted

Let's say your matrix is A, this method does not depend of length of inner lists:

A[[All, All, -1]] = A[[All, All, -1]] /. {x -> y, y -> x};
A

This one doesn't even care about the depth of the array:

A /. a : {(x | y) ..} :> MapAt[# /. {x -> y, y -> x} &, a, {-1}]
share|improve this answer
    
Yes, that works for my problem. Thank you very much! –  Laura Jun 11 at 18:49
    
@Laura I'm glad it does. It is good habit to hold on with an accept a day or two, let's do not discourage others ;) you can still upvote it if you like. Good luck. –  Kuba Jun 11 at 18:51
    
Kuba, I changed your ;; to All so that it will work in v7 too; I hope you don't mind. (It adds a character but it seems clearer too.) Why don't you include a pure MapAt solution using All (for v9)? –  Mr.Wizard Jun 11 at 18:57
    
Never mind the second part; I see kguler beat you to it. –  Mr.Wizard Jun 11 at 18:57
    
@Mr.Wizard I wasn't aware ;; does not work in V7. I guess I was writing Fors back in those days :P I will use All from now on, at least here. –  Kuba Jun 11 at 18:59
dt = RandomChoice[{x, y}, {2, 3, 4}]
(* {{{x, x, x, y}, {x, y, y, y}, {y, y, x, x}}, 
    {{x, x, x, x}, {x, x, y, x}, {x, y, x, y}}} *)

f = MapAt[# /. {x -> y, y -> x} &, #, {{All, All, -1}}] &;
f@dt
(* {{{x, x, x, x}, {x, y, y, x}, {y, y, x, y}}, 
    {{x, x, x, y}, {x, x, y, y}, {x, y, x, x}}} *)
share|improve this answer

Your Answer

 
discard

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.