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

1 view (last 30 days)
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

Accepted Answer

dpb
dpb on 25 Apr 2018
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 Comments
Jeff Miller
Jeff Miller on 26 Apr 2018
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 on 26 Apr 2018
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...

Sign in to comment.

More Answers (0)

Categories

Find more on Tables in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!