Matlab: remove duplicate values

I am new to programming in general and MATLAB, and I am having some problems removing values ​​from the matrix.

I have a tmp2 matrix with values:

tmp2 = [... ... 0.6000 20.4000 0.7000 20.4000 0.8000 20.4000 0.9000 20.4000 1.0000 20.4000 1.0000 19.1000 1.1000 19.1000 1.2000 19.1000 1.3000 19.1000 1.4000 19.1000 ... ...]; 

How to remove the part where there is 1.0 in the left column, but the values ​​on the right are different? I want to save the line from 19.1. I searched for solutions, but found some that delete both lines using the histc function, and that is not what I need.

thanks

+4
source share
3 answers

I saw a solution with a unique one and wanted to give a solution with cycles. You can see which one is faster: D! Perhaps the loop can be improved ...

 clear tmp = [0.6000 20.4000 0.7000 20.4000 0.8000 20.4000 0.9000 20.4000 1.0000 20.4000 1.0000 19.1000 1.1000 19.1000 1.2000 19.1000 1.3000 19.1000 1.4000 19.1000]; ltmp = length(tmp); jj = 1; for ii = 1 : ltmp if ii > 1 if tmp(ii, 1) == tmp(ii - 1, 1) continue end end if ii < ltmp if tmp(ii, 1) == tmp(ii + 1, 1) tmp2(jj,1) = tmp(ii, 1); tmp2(jj,2) = min(tmp(ii, 2),tmp(ii + 1, 2)); else tmp2(jj, 1) = tmp(ii, 1); tmp2(jj, 2) = tmp(ii, 2); end else tmp2(jj, 1) = tmp(ii, 1); tmp2(jj, 2) = tmp(ii, 2); end jj = jj + 1; end 
+1
source

You can do this using unique :

 >> [~,b] = unique(tmp2(:,1)); % indices to unique values in first column of tmp2 >> tmp2(b,:) % values at these rows ans = 0.6000 20.4000 0.7000 20.4000 0.8000 20.4000 0.9000 20.4000 1.0000 19.1000 ... 

By default, unique stores the last unique value that it finds, and the result will be sorted. It happens the way you want / have, so you're in luck :)

If this is not what you want / have, you will have to lose some weight. Removing duplicates that preserve order is as follows:

 % mess up the order A = randperm(size(tmp2,1)); tmp2 = tmp2(A,:) % use third output of unique [a,b,c] = unique(tmp2(:,1)); % unique values, order preserved tmp2(b(c),:) ans = 1.1000 19.1000 1.2000 19.1000 1.0000 20.4000 0.7000 20.4000 1.0000 20.4000 1.4000 19.1000 0.6000 20.4000 0.9000 20.4000 1.3000 19.1000 0.8000 20.4000 ... 

which still saves the last record found. If you want to keep the first record found, use

 % unique values, order preserved, keep first occurrence [a,b,c] = unique(tmp2(:,1), 'first'); 
+7
source

use unique without the 'rows' option

 [C ia ib] = unique( tmp2(:,1) ); C = tmp2( ia, : ); 
+6
source

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


All Articles