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

2 次查看(过去 30 天)
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!

回答(1 个)

Akira Agata
Akira Agata 2020-3-17
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 个评论
Akira Agata
Akira Agata 2020-3-17
Hi Guillaume-san,
Thank you for your additional comment for clarification. Also, thank you for adding a better solution!
Guillaume
Guillaume 2020-3-17
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!

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by