2016-05-22 5 views
0

私は行ベクトルの内側にある2行ベクトルを交換しようとしています。例えば行ベクトルの中で2つの行ベクトルを入れ替える方法は?

:私はランダムなスワップは、A、B、Cの2ことをやりたい

a=[1 2 3]; 
b=[5 3]; 
c=[9 3 7 6]; 
d=[7 5]; 

X1= [ a, b , d, c ]; 

、DはX1の同じ位置のままであり、それらの残りの二つは、X1にシャッフルします。例えば、可能なランダムスワップの一部は以下のとおりです。あなたがしようとしているものに [b,a,d,c] % a and b swap with each other whereas d and c remain at the same place

[d,b,a,c] % a and d swap with each other whereas b and c remain at the same place

[c,b,d,a] % a and c swap with each other whereas b and d remain at the same place ..... .....

+1

この[URL](http://stackoverflow.com/help)を確認してください –

+0

まで、あなたのコンテンツの品質を持ち上げるために有用であろう、私はあなたが求めているもの見当がつかない – excaza

答えて

4

適切かつ安全な方法変数をcellに代入し、セルの要素を置換し、最後に結果を連結します。

特定の順列、たとえば[c, b, a, d]を想像してください。この順列は、マッピングに関して[3, 2, 1, 4]とコード化することができる。配列を生成するコードは、次のとおりです。

% generate input 
a = [1, 2, 3]; 
b = [5, 3]; 
c = [9, 3, 7, 6]; 
d = [7, 5]; 

% generate cell to permute 
tmpcell = {a, b, c, d}; 

% define our permutation 
permnow = [3, 2, 1, 4]; 

% permute and concatenate the result into an array 
result = [tmpcell{permnow}]; 

% check if this is indeed OK: 
disp(isequal(result,[c, b, a, d])) % should print 1 

唯一必要なのは、ランダムな構成を生成することです。これは簡単です:2つのランダムなインデックスを選択して、[1, 2, 3, 4]に入れ替えてください。これを行うには怠惰なオプション:

nvars = length(tmpcell);   % generalizes to multiple variables this way 
idperm = 1:nvars; 
i1 = randi(nvars,1); 
partperm = setdiff(idperm, i1); % vector of remaining indices, avoid duplication 
i2 = partperm(randi(nvars-1,1)); % second index, guaranteed distinct from i1 
permnow = idperm; 
permnow([i1, i2]) = [i2, i1]; % swap the two indices 
+2

私はもっと同意できませんでした。私は、これはOPが要求しているものではないという印象を受けるが、提供されるかなり限られた情報でもっとも良い推測である。とにかく+1。 – patrik

関連する問題