Relative occurance of intersect values

Is there a way to vectorize the below, and/or a better way to go about it?
A = %some set of numbers
B = %another set of numbers
C = intersect(A,B);
for temp = 1:numel(C)
C(temp,2) = numel(find(A==C(temp,1)));
C(temp,3) = numel(find(B==C(temp,1)));
end
I've tried using histcounts(A,C), however that returned 1 fewer bins that required, and just adding an arbitrary additional bin edge to either side does not get histcounts to give me what I'm looking for.

 Accepted Answer

The intersect funciton can output the indices of the intersecting elements. See Intersection of Two Vectors and Their Indices for an illustration.

4 Comments

I do understand this. What I do not understand is how to leverage that to get the information I want. intersect only returns the first index of any given intersecting value, and I would need all indecis for a given value.
The ismember (or ismembertol) functions might be more appropriate —
A = randi(9, 1, 15)
A = 1×15
4 6 5 6 3 1 4 4 2 2 1 9 5 8 2
B = randi(9, 1, 15)
B = 1×15
8 5 8 9 9 4 9 6 6 3 2 6 2 3 1
[Lv,ixb] = ismember(A, B)
Lv = 1×15 logical array
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
ixb = 1×15
6 8 2 8 10 15 6 6 11 11 15 4 2 1 11
I generally prefer those functions.
.
Well, I ended up rewriting my code in such a way that ismember has been very useful as the index map. Thanks!
A = [unique(A(:,1)), accumarray(findgroups(A(:,1)),A(:,2),[],@func)]
B = [unique(B(:,1)), accumarray(findgroups(B(:,1)),B(:,2),[],@func)]
C = intersect(A(:,1),B(:,1))
A2Bmap = ismember(A(:,1),C)
B2Amap = ismember(B(:,1),C)
%more code
As always, my pleasure!

Sign in to comment.

More Answers (0)

Categories

Find more on Communications Toolbox in Help Center and File Exchange

Products

Release

R2019b

Community Treasure Hunt

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

Start Hunting!