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

조회 수: 1 (최근 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개)

카테고리

Help CenterFile Exchange에서 Range and Doppler Estimation에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by