필터 지우기
필터 지우기

Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

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

조회 수: 1 (최근 30일)
hossam eldakroury
hossam eldakroury 2019년 2월 20일
마감: MATLAB Answer Bot 2021년 8월 20일
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

답변 (1개)

KSSV
KSSV 2019년 2월 20일
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
hossam eldakroury
hossam eldakroury 2019년 2월 20일
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 ]

이 질문은 마감되었습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by