# Tip: Transpose a pair of indices of an Array

June 29 2007 by
false
Maple

1

A note added: Although the coding below is correct, it has clearly been superseeded by the following two entries contributed by acer: Entry 1 and Entry 2. As in any fairytale (even though this blog of mine certainly is not) it takes three of something (at least according to the fairytales of my fellow-countryman H. C. Andersen). Todays entry is the third and last (at least for now) in a row of three consecutive ones dealing with manipulations of indices of Arrays. The other two entries are Tip: Index an Array and Tip: Permute the indices of an Array. Whereas permuting the indices of an Array requires all dimensions to be of equal size, transposing a pair indices only requires the dimensions of the two indices in question to be of equal size. By now, at least for those who have read Tip: Index an Array and Tip: Permute the indices of an Array, it probably comes as no surprise that the method uses a procedure of the type index/method, and (yes, you guessed correctly) it originates from "Gravitation". Here it comes:
setIndexTranspose := proc(index1::posint,index2::posint)
global index/transpose:
index/transpose := proc(indices::list,array::Array,value::list)
local index1_,index2_:
if nargs = 2 then
array[op(indices)]:
else
index1_,index2_ := min(index1,index2),max(index1,index2):
array[
seq(indices[i],i=1..index1_-1),
indices[index2],
seq(indices[i],i=index1_+1..index2_-1),
indices[index1],
seq(indices[i],i=index2_+1..nops(indices))
] := value[1]:
end if:
end proc:
end proc:
An example which performs B[i,k,j] := A[i,j,k] for all (i,j,k):
setIndexTranspose(2,3):
A := Array(1..3,1..3,1..3,(i,j,k)->i*j-k^2):
B := Array(transpose,A):
PS: As for Tip: Permute the indices of an Array suggestions of improvements (especially concerning the else-statement, again) are of course quite welcome.