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

1 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Tables 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by