Sam Leak
Sam Leak

Reputation: 33

Finding all sets of a certain length within a vector in Matlab

My original question here (follow up written after) was:

(in Matlab)

"If I have a vector, eg '[1 2 3 4 5 6 7]'.

How can I find every possible set of a specified length within this (e.g. length = 3 -> [1 2 3], [1 2 4] ...)?

I'd like to be able to collect every one of these sets and then to find every permutation of these (I should be able to use 'perm' for this stage right?)."

To follow up on that:

How do I find every possible permutation of every possible set of a specified length within the same vector (the above one is just an example) that contains 1 or more specified numbers (e.g. "within the vector find every set of length 3 that contains the number 1, and then find every permutation of these")

Upvotes: 0

Views: 85

Answers (1)

Robert Seifert
Robert Seifert

Reputation: 25232

To complete Luis' first thought:

v = [ 11, 12, 13, 14, 15, 16 ];
n = 3;

allSets = nchoosek(v,n);

And to get the permutations of every set:

%// output in cell array
output = arrayfun(@(x) perms(allSets(x,:)),1:size(allSets,1),'Uni',0)

%// alltogether
output2 = vertcat(output{:})

Or to make it more complicated in one line:

output2 = reshape(cell2mat(arrayfun(@(x) perms(allSets(x,:)),1:size(allSets,1),'Uni',0)),[],3)

Upvotes: 1

Related Questions