Daniel@0: function [model, partition_size] = fit_partitioned_model(... Daniel@0: inputs, outputs, selectors, sel_sizes, min_size, partition_names, fn_name, varargin) Daniel@0: %function [models, partition_sizes] = fit_partitioned_model(... Daniel@0: % inputs, outputs, selectors, sel_sizes, min_size, partition_names, fn_name, varargin) Daniel@0: % Daniel@0: % Fit models to different subsets (columns) of the input/output data, Daniel@0: % as chosen by the selectors matrix. If there is only output data, set input=[]. Daniel@0: % If there is less than min_size data in partition i, Daniel@0: % we set model{i} = [] Daniel@0: % Daniel@0: % Example: Daniel@0: % selectors = [1 2 1 1 1 Daniel@0: % 1 2 2 1 2] Daniel@0: % sel_sizes = [2 2] so there are 4 models: (1,1), (2,1), (1,2), (2,2) Daniel@0: % We fit model{1} to data from columns 1,4 Daniel@0: % We fit model{2} to no data Daniel@0: % We fit model{3} to data from column 3,5 Daniel@0: % We fit model{4} to data from column 2 (assuming min_size <= 1) Daniel@0: % Daniel@0: % For each partition, we call the specified function with the specified arguments Daniel@0: % as follows: Daniel@0: % model{i} = fn(input(:,cols{i}), output(:,cols{i}), args) Daniel@0: % (We omit input if []) Daniel@0: % partition_size(i) is the amount of data in the i'th partition. Daniel@0: % Daniel@0: % Example use: row 1 of selectors is whether an object is present/absent Daniel@0: % and row 2 is the location. Daniel@0: % Daniel@0: % Demo: Daniel@0: % inputs = 1:5; outputs = 6:10; selectors = as above Daniel@0: % fn = 'fit_partitioned_model_testfn'; Daniel@0: % [model, partition_size] = fit_partitioned_model(inputs, outputs, selectors, [2 2], fn) Daniel@0: % should produce Daniel@0: % model{1}.input = [1 4], model{1}.output = [6 9] Daniel@0: % model{2} = [] Daniel@0: % model{3}.input = [3 5], model{3}.output = [8 10], Daniel@0: % model{4}.input = [2], model{3}.output = [7], Daniel@0: % partition_size = [2 0 2 1] Daniel@0: Daniel@0: Daniel@0: sel_ndx = subv2ind(sel_sizes, selectors'); Daniel@0: Nmodels = prod(sel_sizes); Daniel@0: model = cell(1, Nmodels); Daniel@0: partition_size = zeros(1, Nmodels); Daniel@0: for m=1:Nmodels Daniel@0: ndx = find(sel_ndx==m); Daniel@0: partition_size(m) = length(ndx); Daniel@0: if ~isempty(partition_names) % & (partition_size(m) < min_size) Daniel@0: fprintf('partition %s has size %d, min size = %d\n', ... Daniel@0: partition_names{m}, partition_size(m), min_size); Daniel@0: end Daniel@0: if partition_size(m) >= min_size Daniel@0: if isempty(inputs) Daniel@0: model{m} = feval(fn_name, outputs(:, ndx), varargin{:}); Daniel@0: else Daniel@0: model{m} = feval(fn_name, inputs(:,ndx), outputs(:, ndx), varargin{:}); Daniel@0: end Daniel@0: end Daniel@0: end