MATLAB: Get the index of paired Values using allcomb

allcombarraycombinationsindexpairing

Greetings!
I am using the allcomb function (see here: http://de.mathworks.com/matlabcentral/fileexchange/10064-allcomb-varargin-) to pair values between an arbitrary number of vectors. Works perfectly, I get a resulting array with all possible combinations, but in addition to that I do need the information as to which values actually got paired, so basically the index from the original vectors for every entry in the resulting array. The background is that a lot of values in the original vectors are the same but it still matters for my application which position it is at.
Anybody has an idea on how to do that? Doesn't matter if the informations are added to the same array or in a separate one.
Any help would be much appreciated, thank you!

Best Answer

Instead of creating the cartesian product of the vectors, create the cartesian product of the indices of the vector:
vectors = {randi(100, 1, 20), randi(100, 1, 10), randi(100, 1, 7)}; %demo data
indices = cellfun(@(v) 1:numel(v), vectors, 'UniformOutput', false); %vector of indices
combindices = allcomb(indices{:}); %cartesian product of indices
Then either use this cartesian product to index your vector, or call allcomb on your vector, whichever is faster
%indexing with combindices:
combvectors = cell2mat(cellfun(@(v, i) reshape(v(i), [], 1), vectors, num2cell(combindices, 1), 'UniformOutput', false));
%or call allcomb again
combvectors = allcomb(vectors{:});