How to subset a table in a function based on input arguments
古いコメントを表示
Hello,
I am trying to write a function that subset a table based on the arguments used by the user. If the user doesnt select any arguments, then the function returns all the table contents. If the user uses the input argument 'year' then the function should only return year1 and year2. If the user uses the input argument 'type' then the function should only return type1 and type2. Using the arguments year and type should return year1, year2, type1 and type2.
Thoughts ?
function myfun(year, type, gof)
year1 = {1994, 1994, 1994, 1994, 1994, 1994, 1994, 1994, 1994}.';
year2 = {1995, 1995, 1995, 1995, 1995, 1995, 1995, 1995, 1995}.';
type1 = {'AA', 'AA', 'AA', 'AA', 'AA', 'AA', 'AA', 'AA', 'AA'}.';
type2 = {'BB', 'BB', 'BB', 'BB', 'BB', 'BB', 'AA', 'BB', 'BB'}.';
gof1 = {'CC', 'CC', 'CC', 'CC', 'CC', 'CC', 'CC', 'CC', 'CC'}.';
gof2 = {'DD', 'DD', 'DD', 'DD', 'DD', 'DD', 'DD', 'DD', 'DD'}.';
t = table(year1, type1, year2, type2, gof1, gof2);
year = {'year1', 'year2'};
type = {'type1', 'type2'};
gof = {'gof1', 'gof2'};
if nargin == 0
% do nothing - i.e return all variables by default
else
user_request = {year, type, gof}; %else return table subset depending on arguments used
[~, f_order] = ismember(t.Properties.VariableNames, user_request);
[~, g_order] = sort(f_order);
t = t(:, g_order);
end
file = table2cell(t);
xlswrite('output.xlsx', file);
採用された回答
その他の回答 (0 件)
カテゴリ
ヘルプ センター および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!