how to get common elements of matrix based on another matrix?
Show older comments
hey all
how to get common elements of array1 based on 'rows' array?
array1 = {[1,5,7,2];[1,4,6,2];[1,4,5]}
rows = {[2,3];[1,3];[1,2]}
result{1,1} = {[];[1,2];[1,5]} % compare row1 with row1 in array1 then row1 with row2 then row1 with row3
result{2,1} = {[1,2];[];[1,4]} % compare row2 with row1 in array1 then row2 with row2 then row2 with row3
result{3,1} = {[1,5];[1,4];[]} % compare row3 with row1 in array1 then row3 with row2 then row3 with row3
if we consider rows{1,1} then comparision will be between row 1 and other rows in aaray1 and so on.
11 Comments
Guillaume
on 5 Jan 2018
I do not understand the explanation and do not understand how result is generated. Can you give clearer explanations?
lucksBi
on 5 Jan 2018
Guillaume
on 5 Jan 2018
Be careful with your notation,
row{1} = {[2, 3]}
is not the same as
row{1} = [2, 3]
%or
row(1) = {[2, 3]}
You state that row{1} = [2, 3] and because this is row{1} we compare the first row of array1. We compare it to the rows specified by row{1} so that's 2 and 3. So why, do you then state that "first element is [] because here comparision is row 1 to row 1" when 1 never appears in row{1}?
What if row{1} was [3, 3]? What would result{1} be?
lucksBi
on 5 Jan 2018
Guillaume
on 5 Jan 2018
Yes, but why are you comparing row 1 to row 1, when row{1} only tell you to compare row 1 to row 2 and 3? row{1} is not [1, 2, 3]. That's the bit I don't understand with your logic.
lucksBi
on 5 Jan 2018
lucksBi
on 5 Jan 2018
Birdman
on 5 Jan 2018
My code actually does what you want. Have you tried it?
lucksBi
on 5 Jan 2018
lucksBi
on 5 Jan 2018
Accepted Answer
More Answers (1)
Birdman
on 5 Jan 2018
One approach(with a for loop):
for j=1:size(rows,1)-1
for i=1:size(array1,1)
result{i,j}=array1{i}(ismember(array1{i},rows{i}(j)));
end
end
Note: the ones with no intersect are eliminated, therefore the result is 3x2 cell.
7 Comments
Guillaume
on 5 Jan 2018
I have no idea if this is the answer the OP is looking for (it does not produces the result asked for) but
x(ismember(x, y))
is the same as
intersect(x, y)
as long as there are no repeated elements in x.
lucksBi
on 5 Jan 2018
lucksBi
on 5 Jan 2018
lucksBi
on 5 Jan 2018
Birdman
on 5 Jan 2018
Well, your question is hard to understand and my answer is almost the same what you wanted, so whether taking and modifying it or not is totally up to you.
lucksBi
on 5 Jan 2018
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!