i have one dimensional array and i want to move every non zero element oh that array to exchange position with every zero in each iteration.
조회 수: 2 (최근 30일)
이전 댓글 표시
For example
a=[1 2 3 4 0 0 0 ]
I want all the possible combination through nested for loop (not circular shift)
example of Iterations are like
4 will replace its position with 0 (on the right)
a1=[1 2 3 0 4 0 0]
a2=[1 2 3 0 0 4 0]
a3=[1 2 3 0 0 0 4]
now 4 returns to its original position and 3 will shift its position with 0 (on right on 4) move left place one by one
a4=[1 2 0 4 3 0 0]
a5=[1 2 0 4 0 3 0]
a6=[1 2 0 4 0 0 3]
now 3 returns to its original position and 2 replaces its position with 0 (right of 4) move left place one by one
a7=[1 0 3 4 2 0 0 ]
a8=[1 0 3 4 0 2 0 ]
a9=[1 0 3 4 0 0 2 ]
now 2 reutrns to its original position and 1 replaces its position with 0
a10=[0 2 3 4 1 0 0]
a11=[0 2 3 4 0 1 0]
a12=[0 2 3 4 0 0 1]
댓글 수: 1
John D'Errico
2022년 8월 30일
Are you sure this is what you want? It seems like you might want ALL ways of sorting the elements of the array, and this gives you only a subset of the permutations.
답변 (1개)
the cyclist
2022년 8월 30일
편집: the cyclist
2022년 8월 30일
I think this does what you want:
% Input data
a = [1 2 3 4 0 0 0];
% Find the indices of the non-zeros and the zeros
idxNotZero = find(a~=0);
idxZero = find(a==0);
% Preallocate the array c that holds the output
numberCombos = numel(idxNotZero).*numel(idxZero);
c = zeros(numberCombos,numel(a));
% For all pairs of zero and non-zero elements, write a new row that swaps
% them
nr = 0;
for inz = idxNotZero
for iz = idxZero
nr = nr + 1;
c(nr,:) = swapIt(a,inz,iz);
end
end
c
% Function that swaps two elements of a vector, given the element indices
function [out] = swapIt(a,i,j)
out = a;
out([i j]) = out([j i]);
end
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!