Is there a better way to write this short function, without the 'for' loop?

1 回表示 (過去 30 日間)
Jeff Miller
Jeff Miller 2018 年 4 月 24 日
コメント済み: dpb 2018 年 4 月 26 日
function Rows = FindMatchingTableRows(Tbl,VarNames,VarVals)
% Find the numbers of the rows in Tbl with the values
% given in VarVals on the variables given in VarNames.
%
% Tbl is a table.
% VarNames is a cell array of strings naming k variables in Tbl.
% VarVals is an array of k numeric values specifying the desired
% values of the VarNames variables.
% Rows is a vector with the numbers of the Tbl rows having the desired
% values on the indicated variables.
k = numel(VarVals);
Tol = .001;
matching = true(height(Tbl),1);
for kidx=1:k
matching = matching & (abs(Tbl.(VarNames{kidx})-VarVals(kidx))<=Tol);
end
Rows = find(matching);
end
Thanks

採用された回答

dpb
dpb 2018 年 4 月 25 日
mtch=ismembertol(Tbl(:,VarNames),VarVals,Tol);
but will be array, not vector and if return only the vector result of find will have lost the location other than by serial order overall. That may be good enough, depends on need...
  6 件のコメント
Jeff Miller
Jeff Miller 2018 年 4 月 26 日
Thanks, I think I've got it now. 'byrows',1 is the key. Sorry I didn't pick that up from the documentation.
dpb
dpb 2018 年 4 月 26 日
Ayup, if the match is for the group as a whole...that wasn't totally clear initially which is why I was pointing out the result was going to be an array and find would turn the array into a vector so that would only have the serial location in the array coming back...

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by