フィルターのクリア

In table, how to select values in one column based on values in another column?

23 ビュー (過去 30 日間)
Doheon Lee
Doheon Lee 2021 年 4 月 17 日
コメント済み: Doheon Lee 2021 年 4 月 20 日
As given in the title, I like to call values in one table based on values in anothe column. I have a follwoing table.
T = table({'a'; 'b'; 'c'; 'd'; 'e'}, [1;2;3;4;5], 'variablenames', {'name', 'value'});
I like to call elements in the 'value' column, for 'd', 'b', 'e' in the 'name' column. So the expected result is as below
result =
4.00
2.00
5.00
I can do this with the following codes.
order = {'d', 'b', 'e'};
[Lia, Locb] = ismember(T.name, order);
order_chosen = T.value(Lia);
Locb = nonzeros(Locb);
result = order_chosen(Locb);
However, as you can see, lines seem too many for such a relatively simple outcome. So I wonder if there is way to do the samething efficiently with shorter lines.
Thank you for any help in advance.

採用された回答

Cris LaPierre
Cris LaPierre 2021 年 4 月 17 日
The simplest way to do this is using logical indexing, but that doesn't preserve the order. That makes it a more challenging problem to solve. Still, it can be done in fewer lines. I suggest using find.
T = table({'a'; 'b'; 'c'; 'd'; 'e'}, [1;2;3;4;5], 'variablenames', {'name', 'value'});
% Find rows corresponding to names, preserving order
[rows,~]=find(T.name==["d","b","e"]);
result = T(rows,"value")
result = 3×1 table
value _____ 4 2 5
  1 件のコメント
Doheon Lee
Doheon Lee 2021 年 4 月 20 日
it works perfectly! Thank you very much for the help.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Distribution Plots についてさらに検索

タグ

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by