compare two matrix and keep only the elements in common

Hi, I am a beginner in matlab, and I need to compare to matrix and then keep only the elements present in both matrix in my 1st matrix (s(1).r). For this I compare the first column of each matrix. I've read the documentation and tried to write a code with ismember:
Lia = ismember(s(1).r(:,1), res_select(:,1)) ;
for ind = length(s(1).r)-1 : -1 : 1
if Lia(ind)==0
s(1).r(ind,:)=[];
end
end
I think something is wrong, because I am supposed to find 1987 elements in common and I found 1988...so close! Where is my mistake, or is there an easier way to do this? Thank you!! Aude

 採用された回答

KSSV
KSSV 2016 年 11 月 21 日
編集済み: KSSV 2016 年 11 月 21 日

1 投票

We don't have data to check your code. Note that, You need not to run a loop...simply use, s(1).r(Lia,:) to get the common elements.
As you have two sets and you want to pick the common elements, you can find intersection of both the arrays. Intersection gives you common elements. doc intersect.
Sometimes depending on the floating point numbers, ismember/ intersect may not work. That case, you need to fix a tolerance value and use ismemebrtol. doc ismembertol.

3 件のコメント

Aude Rapet
Aude Rapet 2016 年 11 月 21 日
Thank you very much KSSV!
I used intersect:
[Cc,ia,ib] = intersect(res_select(:,1),s(1).r(:,1)) ;
and then I tried to remove the non-in common values:
s(1).r(ib,:)=[];
But it is not working, at the end I find 48 values and I should find 1987. Do you know another way to remove the values I don't want to keep after intersect?
Thank you for your reply!
KSSV
KSSV 2016 年 11 月 21 日
You need not to remove the elements, Cc itself will have all common elements, what is length(Cc)?
Aude Rapet
Aude Rapet 2016 年 11 月 22 日
Ah yes you are right, length (Cc) is 1987! thank you very much for your help!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

質問済み:

2016 年 11 月 21 日

コメント済み:

2016 年 11 月 22 日

Community Treasure Hunt

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

Start Hunting!

Translated by