Finding rows that have only two unique clusters of values with a spread of +/- 1

2 vues (au cours des 30 derniers jours)
Raghavasimhan Thirunarayanan
Commenté : Guillaume le 17 Mar 2020
Hello all,
Let us assume that there is a matrix as following:
Z=[a a a a b b; a a b b b a; a a b c b b]
Also assume that we do not know apriori where the rows with just two unique values will lie in a large matrix.I can extract the rows having only two unique elements easily by using unique function in a for loop.
for i=1:size(Z,1)
Z(unique(Z(i,:))<=2,:)
end
Now if my matrix is the following:
Z=[a-1 a+1 a+1 a b-1 b; a-1 a b b+1 b a; a a+1 b-1 c b+1 b]
The first two rows have two unique cluster of values 'a' and 'b' with a spread of maximum +/- 1. How do I extract the two rows in this case?
Thanks!

Réponses (1)

Akira Agata
Akira Agata le 17 Mar 2020
How about using uniquetol function?
The following is an example:
% Sample matrix (a = 5, b = 10, c = 15 in your matrix)
Z = [5-1 5+1 5+1 5 10-1 10; 5-1 5 10 10+1 10 5; 5 5+1 10-1 15 10+1 10];
delta = 2; % -> to detect unique value within +/-1 variation
idx = false(size(Z,1),1);
% Check whether each row has <=2 unique values within +/-1 variation or not
for kk = 1:size(Z,1)
tol = delta/max(Z(kk,:));
if numel(uniquetol(Z(kk,:),tol)) <= 2
idx(kk) = true;
end
end
% Extract the target rows
Z = Z(idx,:);
  5 commentaires
Akira Agata
Akira Agata le 17 Mar 2020
Hi Guillaume-san,
Thank you for your additional comment for clarification. Also, thank you for adding a better solution!
Guillaume
Guillaume le 17 Mar 2020
Raghavasimhan Thirunarayanan's answer moved to comment here:
@ Akira-san
It should be 2 if we do not know 'a' apriori and it differs by more than 2. But in this case since I know 'a', it should be 3. I was wondering how it will affect the above solution. I will try it out once I get home so that I can access matlab.
@Guillame.. Thanks I will try it out!

Connectez-vous pour commenter.

Tags

Produits


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by