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.

1 次查看(过去 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
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
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
c = 12×7
0 2 3 4 1 0 0 0 2 3 4 0 1 0 0 2 3 4 0 0 1 1 0 3 4 2 0 0 1 0 3 4 0 2 0 1 0 3 4 0 0 2 1 2 0 4 3 0 0 1 2 0 4 0 3 0 1 2 0 4 0 0 3 1 2 3 0 4 0 0
% 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

类别

Help CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by