MATLAB: How to split a vector into small subvectors based on condition

matrix manipulation

how can i split a vector into smaller sub vectors, such that the sum of each vectors is less than N
N = 60
V = [30 35 24 15 14 48];

Best Answer

From your other question: https://www.mathworks.com/matlabcentral/answers/510716-compute-from-a-set-of-parameters. I suspect that you want to find all distinct combination of elements where the sum is less than 60 while keeping the number of trips to a minimum. The following code will find an optimal solution; however, it will only work if the number of elements of V is small (say less than 20). The solution have exponential time and space complexity, so the required resources will grow very quickly. For large number of variables, I would recommend using some greedy method, which can give a sub-optimal solution.
N = 60;
V = [30 35 24 15 14 48];
a = mat2cell(repmat([0 1], numel(V), 1), ones(size(V)), 2);
combs = logical(combvec(a{:})'); % create all possible combinations
combs(1, :) = []; % remove a trivial combination
cost = sum(combs.*V, 2);
valid_index = cost < N;
valid_combs = combs(valid_index, :);
valid_costs = cost(valid_index);
[valid_costs, index] = sort(valid_costs, 'descend');
valid_combs = valid_combs(index, :);
optimal_combs = logical([]);
while ~isempty(valid_combs)
current_comb = valid_combs(1,:);
optimal_combs = [optimal_combs; current_comb];
index = any(valid_combs(:, current_comb) == valid_combs(1, current_comb), 2);
valid_combs(index, :) = [];
end
result = {};
for i=1:size(optimal_combs,1)
result{i} = V(optimal_combs(i,:));
end