Filter Table with Generalized Values

I have the following table say t =
Id Age Gender Country
-- ----- --------- ---------
1 10 M US
2 20 F CA
3 20 F US
4 10 M CA
5 10 M CA
I have another array say col_name with values { Age = 20, Gender = F }
Values of col_name change .. for example col_name = { Age = 10, Gender = M, Country = CA }
or col_name = { Age = 10 }
My goal is to write a genealized function such that when i pass col_name ( whatever be its value ) it should be able to get me a filtered set from t
Is there an function for t that can help me get the filtered result set if I passed col_name ?
ex = t.<some_filter_function>( col_name = { Age = 20, Gender = F } )
should give me
Id Age Gender Country
-- ----- --------- ---------
2 20 F CA
3 20 F US

 採用された回答

Geoff Hayes
Geoff Hayes 2020 年 6 月 29 日

0 投票

Neeraj - how about trying something like
filteredTable = t(t.Age == 20 & strcmp(t.Gender, 'F'), :)
or are you hoping for something a little more general?

3 件のコメント

Neeraj Singh
Neeraj Singh 2020 年 6 月 29 日
Hey Geoff, Thank you . I was hoping for a more general arrangement. In this solution you suggested, my Filtering_Function call to 't' would need to be aware that there is Age and Gender in the table "col_name".
If say for example the next loop of values for "col_name" = {Age: 10, Country: "CA"}, then the above solution would not work.
somehow it needs to be something like this -> t.Filter_Function( col_name )
so whatever value col_name gets Filter_Function should be able to parse through that
Geoff Hayes
Geoff Hayes 2020 年 6 月 29 日
Well you could create a function that might do this for you:
function [myTable] = filterTable(myTable, filterObj)
filterNames = fields(filterObj);
for k = 1:length(filterNames)
filterName = filterNames{k};
tableVariables = myTable.Properties.VariableNames;
if ismember(filterNames{k}, tableVariables)
filterValue = getfield(filterObj, filterName);
if ischar(filterValue)
myTable = myTable(strcmp(myTable.(filterName),filterValue), :);
elseif isnumeric(filterValue)
myTable = myTable(myTable.(filterName) == filterValue, :);
else
fprintf('Unhandled filter for %s.\n', filterName);
end
end
end
And then you would create a filter object and call this function like
filterObj.Age = 20;
filterObj.Gender = 'F';
filteredTable = filterTable(t, filterObj);
Neeraj Singh
Neeraj Singh 2020 年 7 月 1 日
Thank you

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangePerformance and Memory についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by