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
  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
      
      
 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
추가 답변 (0개)
참고 항목
카테고리
				Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!