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 Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by