Gnu Octaveにおけるipermuteのバグ

どうやらOctaveのipermuteにはバグがあるらしく,ググれば以下のような報告を見つけることができる.
ipermute function does not perform appropriate permutation of tensor modes
まだ,3.2系だと治っていないっぽいので,対処法をメモしておく.


まず,permuteというのは,転置を一般化したもので,次元の順番を変更することができます.
Rearrange dimensions of N-D array - MATLAB
ipermuteはその逆.
Inverse permute dimensions of N-D array - MATLAB
例を示すと以下のようになる.

>> dim = [2 3 4]; % xの配列次元
>> x = reshape(1:prod(dim), dim) % xの作成
ans(:,:,1) =

        1        3        5
        2        4        6

ans(:,:,2) =

        7        9       11
        8       10       12

ans(:,:,3) =

       13       15       17
       14       16       18

ans(:,:,4) =

       19       21       23
       20       22       24

>> y = permute(x, [2 1 3]) % 配列次元1と2の入れかえ
ans(:,:,1) =

        1        2
        3        4
        5        6

ans(:,:,2) =

        7        8
        9       10
       11       12

ans(:,:,3) =

       13       14
       15       16
       17       18

ans(:,:,4) =

       19       20
       21       22
       23       24

>> z = ipermute(y, [2 1 3]) % 元に戻す
ans(:,:,1) =

        1        3        5
        2        4        6

ans(:,:,2) =

        7        9       11
        8       10       12

ans(:,:,3) =

       13       15       17
       14       16       18

ans(:,:,4) =

       19       21       23
       20       22       24


ipermuteが正確に動いてない場合は,次のように新たにipermuteを作ればよい.

function y = ipermute(x, order)

iorder(order) = 1:max(order);
y = permute(z, iorder);