How to find unique combinations between two columns in a cell array

조회 수: 5 (최근 30일)
Hi,
I am trying to find all the unique combinations between two columns in a cell array so I can identify if a given sensor has different numbers associated to it. The code below almost works: it does identify that there two numbers associated to sensor2 (98 and 97) but it does not identify that there are two numbers associated to sensor3 (also 98 and 97). The problem comes from the fact that the numbers are not necessarily unique (which can be confusing). It is the combination of the 2 columns that is unique, not the number (99, 98, 97).
So how can I fix the code below so it identifies if a given sensor has more than one number associated to it?
test = {'sensor1', 'sensor1', 'sensor2', 'sensor2', 'sensor3', 'sensor3'; '99' '99' '98' '97' '98' '97'}';
[~, k] = unique(test(:, 2), 'stable')
info = test(k, :);
if numel(info(:, 1)) ~= numel(unique(info(:, 1)))
[x, ~, y] = unique(info(:, 1));
z = hist(y, unique(y));
duplicated_sensor = x(z > 1);
fprintf('Warning! The serial number is not unique for the following sensor: %s\n', duplicated_sensor{:})
else
fprintf('The serial numbers are unique for all sensors')
end
Thank you,

채택된 답변

Andrei Bobrov
Andrei Bobrov 2019년 9월 1일
편집: Andrei Bobrov 2019년 9월 1일
test = {'sensor1', 'sensor1', 'sensor2', 'sensor2', 'sensor3', 'sensor3';
'99' '99' '98' '97' '98' '97'}'
T = cell2table(test);
T.test2 = str2double(T.test2 );
out = varfun(@(x)x(:)',T,'GroupingVariables','test1');
  댓글 수: 1
012786534
012786534 2019년 9월 2일
Hello Mr. Bobrov,
I could modify your answer to it make it work. Like so:
test = {'sensor1', 'sensor1', 'sensor2', 'sensor2', 'sensor3', 'sensor3';
'99' '99' '98' '97' '98' '97'}'
T = cell2table(test);
T.test2 = str2double(T.test2 );
out = varfun(@(x)x(:)',T,'GroupingVariables','test1');
for i = 1 : height(out)
j = out(i,:);
if length(unique(j.Fun_test2(1, :))) > 1
fprintf('Warning! The serial number is not unique for %s\n', j.test1{1, :})
else
fprintf('The serial number is unique for %s\n', j.test1{1, :}')
end
end
Thank you

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Graphics Object Programming에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by