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

1 vue (au cours des 30 derniers jours)
012786534
012786534 le 11 Jan 2020
Commenté : 012786534 le 12 Jan 2020
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);

Réponse acceptée

Meg Noah
Meg Noah le 11 Jan 2020
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

Plus de réponses (0)

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by