How to retrieve table data based on matched variable

58 ビュー (過去 30 日間)
Bruce Elliott
Bruce Elliott 2019 年 6 月 21 日
コメント済み: Bruce Elliott 2019 年 6 月 21 日
<Note: I think this might be a database question, but I'd like to know if I can do what I wanted using Matlab tables.>
I have a table that includes a variable that has a unique value for each row - let's call it the 'key'. I have determined that I am interested in the rows that match a given array of values for the key, and I'd like to retrieve data for for those rows. I can easily do this in a for loop:
% I have determined that I am interested in the rows that match the key values in myKeys, and
% I would like to retrieve the values of myTable.Var1 for those row.
myKeys = [1;3;7;8;9];
myData = NaN(5,1);
for n = 1:5
myData(n) = myTable.Var1(myTable.key==myKeys(n));
end
Is there any way to do this without an explicit for loop? It feels like I should be able to use logical indexing in some way, but I haven't come up with it.

回答 (1 件)

Ramnarayan Krishnamurthy
Ramnarayan Krishnamurthy 2019 年 6 月 21 日
編集済み: Ramnarayan Krishnamurthy 2019 年 6 月 21 日
You are correct in that you can use logical indexing to solve this without loops. Here is a possible approach:
% Extract logical indices of the matched keys
idx = ismember(myTable.key, myKeys);
% Access the table for these specific rows
myTable(idx,:)
HTH
  1 件のコメント
Bruce Elliott
Bruce Elliott 2019 年 6 月 21 日
I had thought of something like that, but the potential problem is that the call
idx = ismember(myTable.key,myKeys);
tells me which rows match the values in myKeys, but it does not preserve the order. In other words, I don't know which rows matched which key values in the array myKeys.
That will make it difficult to produce an array of values from the table that are ordered to match myKeys.

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

カテゴリ

Help Center および File ExchangeGraphics Object Programming についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by