2014-12-14 9 views
6

Ho una matrice con righe con numeri ripetuti. Voglio trovare quelle file e sostituirle con una riga fittizia in modo da mantenere costante il numero di righe della matrice.Trova e sostituisci le righe di un array con numero ripetuto da una riga prestabilita

Dummy_row = [1 2 3] 

(5x3) Matrix Un

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] 

Ho provato quanto segue quale cancellato le righe con numeri ripetuti.

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,:) 

Potete aiutare, per favore?

+0

Come può questo codice essere modificato in modo tale che essa sostituisce anche le righe con almeno uno zero con il Dummy_row? –

risposta

3

bsxfun base solutio n -

%// 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) 

Codice run -

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 
+1

Molto bello Divakar – Rashid

+0

Unico inconveniente: sarà comunque necessario utilizzare 'sort (A, 2)' per generalizzare questo aspetto alle matrici con più di 3 colonne. – knedlsepp

+1

@knedlsepp È necessario modificare dummy_row '[1 2 3]' per questo, il resto del codice rimane lo stesso. – Divakar

3

Vedere se questo funziona per voi,

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; 

dà,

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

Edit è necessario

Non molti cambiamenti, provate questo,

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; 
+1

Ti stavo aspettando. Sofisticata! +1 – mehmet

+0

Funziona! Grazie mille Mehmet. –

+0

Grazie @Kamtal! Come può essere modificato questo codice in modo tale da sostituire anche le righe che hanno almeno uno zero con il Dummy_row? –

3

è possibile utilizzare il seguente:

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

Questo potrebbe essere il più veloce! – Divakar

+0

Sì sicuramente! Grazie mille Divakar. –

+0

Grazie @knedlsepp! Come posso modificare questo codice in modo tale che sostituisca anche qualsiasi riga che abbia almeno uno zero con Dummy_row? –

Problemi correlati