Output of the row of a vector which has the same entry as a second vector

1 回表示 (過去 30 日間)
Matt
Matt 2012 年 12 月 1 日
Hello,
Problem: Two vectors a and b. Id like to know in which row of the vector a, the entries of a and b are the same. Output vector r. if a entry in b occurs twice/triple/... the output of the row should also be twice/triple/...
I tried it like this:
a=[1 3 5 8 9 10 13 16]';
b=[2 5 1 1 8 8 8]';
r=find(ismember(a,b))
Solution: r =[1;3;4]
desired solution: r =[1;1;3;4;4;4]
Thanks in advance for your help!
  1 件のコメント
Andrei Bobrov
Andrei Bobrov 2012 年 12 月 1 日
編集済み: Andrei Bobrov 2012 年 12 月 1 日
[c,d] = ismember(sort(b),a)
r = d(c);

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

採用された回答

Matt Fig
Matt Fig 2012 年 12 月 1 日
編集済み: Matt Fig 2012 年 12 月 1 日
You were close, but you want to switch the order of the arguments to ISMEMBER and use the two output call.
% Original data
a=[1 3 5 8 9 10 13 16]';
b=[2 5 1 1 8 8 8]';
% Get R
[H,R] = ismember(b,a);
R = sort(R(H)) % Do you really need it sorted??

その他の回答 (1 件)

Azzi Abdelmalek
Azzi Abdelmalek 2012 年 12 月 1 日
編集済み: Azzi Abdelmalek 2012 年 12 月 1 日
a=[1 3 5 8 9 10 13 16]';
b=[2 5 1 1 8 8 8]';
un=ones(numel(b),1)
out=cell2mat(arrayfun(@(x) un(b==a(x))*x,(1:numel(a))','un',0))

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by