Find and replace rows of an array with a repeated number with a fixed given string

I have a matrix having rows with duplicate numbers. I want to find these rows and replace them with a dummy row to keep the number of rows of the matrix constant.

Dummy_row = [1 2 3] 

(5x3) Matrix A

 A = [2 3 6; 4 7 4; 8 7 2; 1 3 1; 7 8 2] 

(5x3) Matrix new_A

 new_A = [2 3 6; 1 2 3; 8 7 2; 1 2 3; 7 8 2] 

I tried the following, which removed duplicate string.

 y = [1 2 3] w = sort(A,2) v = all(diff(t,1,2)~=0|w(:,1:2)==0,2) % When v is zero, the row has repeated numbers z = A(w,:) 

Can you help?

+6
source share
3 answers

bsxfun solution -

 %// Create a row mask of the elements that are to be edited mask = any(sum(bsxfun(@eq,A,permute(A,[1 3 2])),2)>1,3); %// Setup output variable and set to-be-edited rows as copies of [1 2 3] new_A = A; new_A(mask,:) = repmat(Dummy_row,sum(mask),1) 

Code Execution -

 A = 2 3 6 4 7 4 8 7 2 1 3 1 7 8 2 new_A = 2 3 6 1 2 3 8 7 2 1 2 3 7 8 2 
+3
source

See if this works for you

 A= [ 2 3 6; 4 7 4; 8 7 2; 5 5 5; 1 8 8; 1 3 1; 7 8 2 ]; Dummy_row = [1 2 3]; b = diff(sort(A,2),1,2); b = sum(b == 0,2); b = b > 0; c = repmat(Dummy_row,sum(b),1); b = b' .* (1:length(b)); b = b(b > 0); newA = A; newA(b,:) = c; 

gives

 newA = 2 3 6 1 2 3 8 7 2 1 2 3 1 2 3 1 2 3 7 8 2 

Edit

Don't need a lot of changes, try this,

 Dummy_row = [1 2 3]; b = sum(A == 0,2); b = b > 0; c = repmat(Dummy_row,sum(b),1); b = b' .* (1:length(b)); b = b(b > 0); newA = A; newA(b,:) = c; 
+3
source

You can use the following:

 hasRepeatingNums = any(diff(sort(A, 2), 1, 2)==0, 2); A(hasRepeatingNums,:) = repmat(Dummy_row, nnz(hasRepeatingNums), 1); 
+3
source

Source: https://habr.com/ru/post/979588/


All Articles