Info
This question is closed. Reopen it to edit or answer.
loop till condition met of swapping all repeated value of same column
1 view (last 30 days)
Show older comments
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
0 Comments
Answers (1)
KSSV
on 20 Feb 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 Comment
This question is closed.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!