MathGroup Archive 2001

[Date Index] [Thread Index] [Author Index]

Search the Archive

exchanging 2 elements in a list

  • To: mathgroup at smc.vnet.net
  • Subject: [mg27578] exchanging 2 elements in a list
  • From: Richard Fateman <fateman at cs.berkeley.edu>
  • Date: Wed, 7 Mar 2001 04:08:29 -0500 (EST)
  • Organization: University of California, Berkeley
  • Sender: owner-wri-mathgroup at wolfram.com

Actually, I wanted to exchange 2 rows in a matrix,
but writing this program I found I could not even
exchange 2 elements in a simple list by the first
two (most obvious) programs I wrote.  The third
works. So does the fourth.

Anyone care to explain why the first 2 fail?
(Typing them in to a system does not really explain
that much.)

try Exchangitems[{a,b,c,d,e,f},2,4] which should
result in {a,d,c,b,e,f}.
Naturally it should not SET any of the variables
a,b,c,... . version 2 sets b to the value d.


Exchangeitems1[m_,r_Integer,s_Integer]:=
Block[{temp=m[[r]]},
       m[[r]]=m[[s]];
       m[[s]]=temp;
       m];


Exchangeitems2[m_,r_Integer,s_Integer]:=
Block[{temp},
       temp=m[[r]];
       m=ReplacePart[m,m[[s]],{r}];
       m=ReplacePart[m,temp,{s}];
       m];


(* this works by adding a useless variable *)
Exchangeitems[k_,r_Integer,s_Integer]:=
Block[{m,temp},
       m=k;   
       temp=m[[r]];
       m=ReplacePart[m,m[[s]],{r}];
       m=ReplacePart[m,temp,{s}];
       m];

(*Here is a more "functional" version *)

ei[k_, low_, hi_]:= ei[k,hi,low] /; low>hi;
ei[k_, low_, hi_]:= k /; low==hi;
ei[k_, low_, hi_] := 
  Flatten[{Take[k, {1, low - 1}], {k[[hi]]}, 
      Take[k, {low + 1, hi - 1}], {k[[low]]}, Drop[k, hi]}, 1];

(*and here is an APL-style version*)


ei2[k_,r_,s_]:=Table[Switch[j,r,k[[s]],
                              s,k[[r]],
                              _,k[[j]]],
                   {j,1,Length[k]}];



Is there a nice, efficient, (and correct) program to do this?


Perhaps there is a better way to do this


  • Prev by Date: Re: Mathematica can talk!
  • Next by Date: Re: notebook question
  • Previous by thread: RE: What is the difference equation of a Butterworth filter?
  • Next by thread: Re: Re: controlling the size of tick marks