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 CenterFile Exchange에서 Tables에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by