Help turning a permutation function into a script.

조회 수: 1 (최근 30일)
tban
tban 2017년 5월 7일
답변: Andrei Bobrov 2017년 5월 7일
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!

답변 (1개)

Andrei Bobrov
Andrei Bobrov 2017년 5월 7일
M = V(fliplr(fullfact(ones(1,N)*numel(V))))

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by