Suppose a row vector x=1:8 and another vector of same size z=[1 1 0 1 1 0 1 1].I want to swap element in x according to element in z if z==1 then swap the postion of element of x else z==0 element of x should be in same position in vector.

3 ビュー (過去 30 日間)
The number of swap should be equal to number of one in vector z divide by 2 if even ones else plus one divide by 2.The value of z change after each iteration so logic should be universal.
  4 件のコメント
amit chatterjee
amit chatterjee 2017 年 5 月 24 日
x=[1 2 3 4 5 6 7 8] and element of x randomly swap for example z=[1 1 0 1 1 1 1 0] then x[1] should swap because z[1] is equal to one and x[3] will have same element because z[3] is 0 and swapping is such that no element is repeated in x.e.g x[1] become x[2] and x[2] become x[4].
nitin  jain
nitin jain 2017 年 6 月 10 日
The expected output should be like x=[4 6 3 1 7 2 5 8].whenever z==1 Swap the x element at that postion of x randomly while index of x correspond to x==0 should not be swapped.

サインインしてコメントする。

採用された回答

Jan
Jan 2017 年 5 月 24 日
編集済み: Jan 2017 年 5 月 24 日
Guessing that you want to swap the elements randomly:
x = rand(1, 8); % Test data
z = [1 1 0 1 1 0 1 1];
xf = x(z == 1);
n = sum(z); % Or: numel(xf)
p = randperm(n, n); % Faster than randperm(n)
x(z) = xf(p);
This does not guarantee, that the elements at z==1 are changed. If you need this, try: FEX: Shuffle:
p = Shuffle(n, 'derange', n)
Or if you have installed Shuffle already:
x(z==1) = Shuffle(x(z==1));
  10 件のコメント
nitin  jain
nitin jain 2017 年 6 月 14 日
@stephan thank you for your answer, it is working for me.
Jan
Jan 2017 年 6 月 19 日
@Stephen: Just a note: idx = randperm(n,n) is more efficient with the 2nd input.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by