フィルターのクリア

How to subset a table in a function based on input arguments

2 ビュー (過去 30 日間)
012786534
012786534 2020 年 1 月 11 日
コメント済み: 012786534 2020 年 1 月 12 日
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);

採用された回答

Meg Noah
Meg Noah 2020 年 1 月 11 日
Can just use an anonymous function:
clc
close all
clear all
getVarsetTable = @(t,userPrefix) t(:,contains(t.Properties.VariableNames,userPrefix));
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);
t1 = getVarsetTable(t,{'year','type'});
t2 = getVarsetTable(t,{'year','gof'});
Or if you really want a separate function
function [t] = getVarsetTable(t,userPrefix)
idx = contains(t.Properties.VariableNames,userPrefix);
t = t(:,contains(t.Properties.VariableNames,userPrefix));
end

その他の回答 (0 件)

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by