Table: Add collumn with conditional
1 view (last 30 days)
Show older comments
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 Comments
Answers (0)
See Also
Categories
Find more on Graph and Network Algorithms in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!