登录论坛

查看完整版本 : [求助]有谁知道怎么做排列?请大家帮忙!!1


zhyt
2009-03-17, 07:31
比如一个4*3的矩阵,对他的行做全排列,得到A44共24个矩阵。
请大家帮忙!!!

zhyt
2009-03-17, 12:13
有人会么?
我用循环做了一个,好麻烦啊
谁会简单一点的?

applef
2009-03-17, 12:33
离散数学上有。
这是我以前编的,你改改用。

function allPerm = getAllPermutation(iNUM)
firstPerm = [1:iNUM];
endPerm = [iNUM:-1:1];
rowPerm = prod([1:iNUM]);
curID = 1;
try
allPerm = zeros(rowPerm,iNUM);
catch
error('Can''t creat so much permutation');
end
while ~isequal(firstPerm,endPerm)
allPerm(curID,:) = firstPerm;
firstPerm = getNextPerm(firstPerm);
curID = curID + 1;
end
allPerm(curID,:) = endPerm;

function nextPermutation=getNextPerm(curPermutation)
% getNextPerm:
% get next permutation use method from P288 in
% [Discrete Mathematics and Its Applications(4th)]
lenP = length(curPermutation);
j = lenP - 1;
nextPermutation = curPermutation;
while nextPermutation(j) > nextPermutation(j+1)
j = j - 1; % j 是使得a(j)<a(j+1)的最大下标
end
k = lenP;
while nextPermutation(j) > nextPermutation(k)
k = k - 1; % a(k) 是在a(j)右边大于a(j)的最小整数
end
% change a(k) , a(j)
temp= nextPermutation(j);
nextPermutation(j) = nextPermutation(k);
nextPermutation(k) = temp;

% 把j位以后的排序尾部按递增顺序排列
r = lenP;
s = j + 1;
while r > s
% change a(r) , a(s)
temp = nextPermutation(r);
nextPermutation(r) = nextPermutation(s);
nextPermutation(s) = temp;
r = r - 1;
s = s + 1;
end