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 Ansichten (letzte 30 Tage)
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 Kommentar
John D'Errico
John D'Errico am 30 Aug. 2022
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.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

the cyclist
the cyclist am 30 Aug. 2022
Bearbeitet: the cyclist am 30 Aug. 2022
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

Kategorien

Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by