Help turning a permutation function into a script.

1 view (last 30 days)
function [M, I] = permn(V, N)
narginchk(2,3);
if fix(N) ~= N || N < 0 || numel(N) ~= 1 ;
error('permn:negativeN','Second argument should be a positive integer');
end
nV = numel(V) ;
if nargin==2, % PERMN(V,N) - return all permutations
if nV==0 || N == 0,
M = zeros(nV,N) ;
I = zeros(nV,N) ;
elseif N == 1,
M = V(:) ;
I = (1:nV).' ;
else
[Y{N:-1:1}] = ndgrid(1:nV) ;
I = reshape(cat(N+1,Y{:}),[],N) ;
M = V(I) ;
end
end
This code takes two inputs and spits out a list of permutations. Example: permn(2:4,3) gives me this output;
2 2 2
2 2 3
2 2 4
2 3 2
2 3 3
2 3 4
2 4 2
2 4 3
2 4 4
3 2 2
3 2 3
3 2 4
3 3 2
3 3 3
3 3 4
3 4 2
3 4 3
3 4 4
4 2 2
4 2 3
4 2 4
4 3 2
4 3 3
4 3 4
4 4 2
4 4 3
4 4 4
I would like to instead feed the V,N into the script as a variable, and store the output in a matrix.
Since narginchk can only be called in a function can i even do this?
Thanks!

Answers (1)

Andrei Bobrov
Andrei Bobrov on 7 May 2017
M = V(fliplr(fullfact(ones(1,N)*numel(V))))

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!