Help turning a permutation function into a script.

1 Ansicht (letzte 30 Tage)
tban
tban am 7 Mai 2017
Beantwortet: Andrei Bobrov am 7 Mai 2017
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!

Antworten (1)

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

Kategorien

Mehr zu Multidimensional Arrays finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by