Look up a value in an incomplete list

2 ビュー (過去 30 日間)
clauper
clauper 2022 年 2 月 21 日
コメント済み: DGM 2022 年 2 月 21 日
I have keys and values like this:
keys = ["a", "b", "c", "d"];
vals = [3,4,2,1];
and I need to look up the values for x, but not all keys exist, e.g.:
x = ["c", "d", "e"];
which should result in:
y = [2, 1, NaN];
The problem I have is that strfind(), matches() yield empty arrays for "e", which leads to errors when looking up in vals.
Also, all arrays are >100k so I would like to avoid a for-loop.

採用された回答

Stephen23
Stephen23 2022 年 2 月 21 日
編集済み: Stephen23 2022 年 2 月 21 日
Simpler and more efficient:
keys = ["a","b","c","d"];
vals = [3,4,2,1];
x = ["c","d","e"];
[idx,idy] = ismember(x,keys);
out = nan(size(x));
out(idx) = vals(idy(idx))
out = 1×3
2 1 NaN

その他の回答 (2 件)

DGM
DGM 2022 年 2 月 21 日
How about:
keys = ["a", "b", "c", "d"];
vals = [1,2,3,4];
x = ["c", "d", "e"];
[~,y] = ismember(x,keys);
y(y==0) = NaN
y = 1×3
3 4 NaN
  2 件のコメント
clauper
clauper 2022 年 2 月 21 日
編集済み: clauper 2022 年 2 月 21 日
This looks promising. However, I need the values in vals, not the indices. I changed vals in the question such that the two can be distinguished.
DGM
DGM 2022 年 2 月 21 日
Oof. I forgot about that.
keys = ["a", "b", "c", "d"];
vals = [11,22,33,44];
x = ["c", "d", "e"];
[m idx] = ismember(x,keys);
y = NaN(size(m));
y(m) = vals(idx(m))
y = 1×3
33 44 NaN

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


clauper
clauper 2022 年 2 月 21 日
I figured it out:
keys = ["a", "b", "c", "d"];
vals = [3,4,2,1];
x = ["c", "d", "e"];
[~, idx] = ismember(x, keys);
keyExists = matches(x, keys);
y = nan(length(x),1);
y(keyExists) = vals(idx(idx~=0))
y = 3×1
2 1 NaN
I don't know if there is a more efficient way but this works.

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by