Table: Add collumn with conditional
显示 更早的评论
How to modify this function to create a better code think in how to get a dynamic output table.
In this simple example below, I have only 3 possible input arguments, but in real-life I have 20 possible input arguments.
function table_out = dynamic_table(varargin)
% Set the valid function input arguments:
input_options = {'array_a', 'array_b', 'array_c'};
% Set the index values of each function input argument:
ARRAY_A_IDX = 1;
ARRAY_B_IDX = 2;
ARRAY_C_IDX = 3;
% Preallocate a valid output table arguments:
output_options = zeros(length(input_options), 1);
% Check each function input argument:
for i = 1:length(varargin{:})
% Check if the input(i) is a valid input option:
[is_valid, opt_idx] = ismember(char(varargin{:}(i)), input_options);
if(is_valid)
% If is a valid option, set as true:
output_options(opt_idx) = true;
else
% This input(i) is not a valid function input argument:
warning('Unable to find the entered field: %s', char(varargin{:}(i)));
end
end
% Set a dummy array content:
array_a = [1; 2; 3];
array_b = [4; 5; 6];
array_c = [7; 8; 9];
%% Construct a dynamic conditional output table:
if((output_options(ARRAY_A_IDX)) & (!output_options(ARRAY_B_IDX)) & (!output_options(ARRAY_C_IDX)))
% Only one output collumn:
table_out = table(array_a);
elseif ((output_options(ARRAY_A_IDX)) & (output_options(ARRAY_B_IDX)) & (!output_options(ARRAY_C_IDX)))
% Two output collumns:
table_out = table(array_a, array_b);
elseif ((output_options(ARRAY_A_IDX)) & (output_options(ARRAY_B_IDX)) & (output_options(ARRAY_C_IDX)))
% Three output collumns:
table_out = table(array_a, array_b, array_c);
end
end
How can I get this 'table_out' with different number of collumns depending of the function input arguments?
3 个评论
Geoff Hayes
2019-1-7
Nycholas - are all input column names of the format 'array_a', 'array_b', 'array_c', etc. or can they be something else? Do you really need to check to see if the input parameters match on these column names or can you just assume that whatever the user is passing in is valid? Where will the data for each column come from? I suspect that it won't be like the dummy array content you have above...
Nycholas Maia
2019-1-7
Nycholas Maia
2019-1-7
回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Language Support 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!