Help turning a permutation function into a script.

1 次查看(过去 30 天)
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 中查找有关 Resizing and Reshaping Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by