Borrar filtros
Borrar filtros

Info

La pregunta está cerrada. Vuélvala a abrir para editarla o responderla.

loop till condition met of swapping all repeated value of same column

1 visualización (últimos 30 días)
hossam eldakroury
hossam eldakroury el 20 de Feb. de 2019
Cerrada: MATLAB Answer Bot el 20 de Ag. de 2021
hi,
i have a matrix A
A=[1 1 2
2 2 3
3 3 4
4 5 6
5 6 7
6 7 8
7 6 26
8 26 27
9 27 28
10 28 29
11 29 30
12 30 31
13 31 32
14 32 33
15 25 29 ];
i want to make a loop which detect repeated values of column no. 3 then swap the repeated value of column 3 with column 2 and keep going until no repeated values in column 3
note:(i want to decide which repeated value i will fix and change the rest)
i make somthing like that
uniqueVals = unique( l(:,3) );
valCount = hist( l(:,3) , uniqueVals )';
for i=1:15
if valCount(i)==2
A(i,[2,3])=A(i,[3,2]);
end
end
but gives error cause it couldnt keep going and keep swapping after values keep change
the desired output
B=[ 1 1 2
2 2 3
3 3 4
4 6 5
5 6 7
6 7 8
7 26 6
8 27 26
9 28 27
10 29 28
11 29 30
12 30 31
13 31 32
14 32 33
15 25 29 ];
as you can see when the detected repeated value is (29) in last row, the columns swapped at row 10 then it swapped at row 10 (so no repeated values at columns 3 as desired) then swapped at row 9 then swapped at row 8 then swapped at 7 then swapped at row 4 and when no repeated value at column the loop stops

Respuestas (1)

KSSV
KSSV el 20 de Feb. de 2019
A=[1 1 2
2 2 3
3 3 4
4 5 6
5 6 7
6 7 8
7 6 26
8 26 27
9 27 28
10 28 29
11 29 30
12 30 31
13 31 32
14 32 33
15 25 29 ];
[c,ia,ib] = unique(A(:,3));
Ncount = histc(A(:,3), c);
B = A ;
rep = nnz(Ncount>1) ;
for i = 1:rep
idx = find(A(:,3)==c(Ncount==i+1)) ;
B(idx(1),2:3) = A(idx(1),3:-1:2) ;
end
  1 comentario
hossam eldakroury
hossam eldakroury el 20 de Feb. de 2019
i tried it but it only swapped row 10 and didnt continue to swap the rest
the result was
B =[ 1 1 2
2 2 3
3 3 4
4 5 6
5 6 7
6 7 8
7 6 26
8 26 27
9 27 28
10 29 28
11 29 30
12 30 31
13 31 32
14 32 33
15 25 29]
as you can see only row 10 swapped but row 9 still got (28) in column 3 which is repeated since row 10 got (28) too, i wanted to keep swapping while moving up till no repeated value in column 3.. i think a while loop would work but i dont know how to do it
i want the result to be like this
B=[ 1 1 2
2 2 3
3 3 4
4 6 5
5 6 7
6 7 8
7 26 6
8 27 26
9 28 27
10 29 28
11 29 30
12 30 31
13 31 32
14 32 33
15 25 29 ]

La pregunta está cerrada.

Community Treasure Hunt

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

Start Hunting!

Translated by