finding elements in a vector from another vector

I'd like to create a vector y with the positions of the elements of x in m.
i.e.
x=0 (first element of x) has and index of 1 in m. So y(1)=1
x=241 (second element of x) has index of 242 in x. So y(2)=242
m and x are in attached

 採用された回答

Star Strider
Star Strider 2020 年 7 月 18 日

0 投票

Try this:
M = load('m.mat');
X = load('x.mat');
m = M.m;
x = X.x;
[~,y] = ismembertol(x, m, 1E-4)
producing:
y =
1
242
937
2001
3306
4695
6001
7065
7759
8001
I checked that separately for a few values using find, and it appears to produce the correct result.
.

8 件のコメント

Paul Rogers
Paul Rogers 2020 年 7 月 18 日
can't make it work since I think m and x are in my script, I don't need to lload them.
Star Strider
Star Strider 2020 年 7 月 18 日
I needed to load them. If they are already in your workspace as ‘x’ and ’m’, just run:
[~,y] = ismembertol(x, m, 1E-4)
You should get the same result that I did.
.
Paul Rogers
Paul Rogers 2020 年 7 月 18 日
編集済み: Paul Rogers 2020 年 7 月 18 日
I did but I get this.
maybe it's because I have r2014b?
Undefined function 'ismembertol' for input arguments of type 'double'.
Star Strider
Star Strider 2020 年 7 月 18 日
編集済み: Star Strider 2020 年 7 月 18 日
The ismembertol function was introduced in the next release, R2015a.
The only work-around I can offer is this loop:
for k = 1:numel(x)
y(k) = find(m <= x(k), 1, 'last');
end
It produces almost the same result. They are identical, except for ‘y(3)’ that using ismembertol is 937 and using find is 936.
EDIT — (18 Jul 2020 at 20:52)
Unfortunately, ismember only works for 4 of the members of ‘x’. However that can be remedied by multiplying them by :
[~,y] = ismember(fix(x*1E+4), fix(m*1E+4))
producing essentially the same result as ismembertol, and the same results as the find loop.
Paul Rogers
Paul Rogers 2020 年 7 月 18 日
編集済み: Paul Rogers 2020 年 7 月 18 日
this worrks better:
[~,y] = ismember(fix(x*1E+4), fix(m*1E+4))
thanks.
Star Strider
Star Strider 2020 年 7 月 18 日
Great!
I did not initially pick up on your posting the Release information as R2014b (so my apologies for that oversight if you posted it originally, since I only checked later).
.
Paul Rogers
Paul Rogers 2020 年 7 月 18 日
I think it's best we don't edit comment so people can read different options and figure it out based on their version
Star Strider
Star Strider 2020 年 7 月 18 日
Noted.

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

その他の回答 (1 件)

Fangjun Jiang
Fangjun Jiang 2020 年 7 月 18 日
編集済み: Fangjun Jiang 2020 年 7 月 18 日

0 投票

[~,y]=ismember(x,m)

カテゴリ

ヘルプ センター および File ExchangeMathematics についてさらに検索

製品

リリース

R2014b

Community Treasure Hunt

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

Start Hunting!

Translated by