How I manually write a function for computing set intersection? (partial code)

2 次查看(过去 30 天)
I am trying to manually write the intersect function that takes two sets and produces the values that are the same within both. for example: {a, b, c} and {a, b, g} should produce a, b. However when I run my code I am just getting a set full of commas as output like this: { , , , , , , , ,}. My code is as follows:
function result = TylerJohnsonIntersect(set1, set2)
uset1 = unique(set1);
uset2 = unique(set2);
for i = 1:length(uset1)
for j = 1:length(uset2)
if uset1{i} == uset2{j}
set3{i} = i;
end
end
end
result = set3;
end
Can anyone point me in the right direction?

回答(1 个)

KSSV
KSSV 2016-9-8
How about this?
function result = TylerJohnsonIntersect(set1, set2)
uset1 = unique(set1);
uset2 = unique(set2);
for i = 1:length(uset1)
for j = 1:length(uset2)
if uset1{i} == uset2{j}
set3(i) = i;
end
end
end
result = set1(set3);
There is command intersect(A,B) in MATLAB. Have a look on that.

类别

Help CenterFile Exchange 中查找有关 Multidimensional Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by