[英]Non-recursive implementation of perms in Matlab, compatible with Coder
我正在嘗試使用編碼器將matlab中的部分函數轉換為c ++。 編碼器不支持perms
功能。 我在代碼中廣泛使用了perms
。 在網上查看后,我發現很少有人建議如何生成不帶perms
的所有排列列表,但這是“手工完成”的,這意味着對於包含3個元素的排列,我們有3個for循環,包含4個元素的我們有4個循環,依此類推。
1:4
示例:
row = 1;
n=a;
Z = zeros(factorial(n),n);
idxarray1=[1:4];
for idx=idxarray1
idxarray2=idxarray1(find(idxarray1~=idx)) ;
for jdx=idxarray2
idxarray3=idxarray2(find(idxarray2~=jdx));
for kdx=idxarray3
idxarray4=idxarray3(find(idxarray3~=kdx)) ;
for mdx=idxarray4
Z(row,:) = [idx,jdx,kdx,mdx];
row = row + 1 ;
end
end
end
end
對於8個元素,我將不得不編寫8個for循環,關於如何將其轉換為n個元素的任何建議? 就像是
for i=n:-1:1
I=[1:n] ;
for j=1:i
J=I(find(I~=j));
... ?
thank you
這里的問題是, perms
使用遞歸,而遞歸是Matlab Coder不支持的語言功能之一。 因此,我們需要做的是提出一個非遞歸的實現。
有趣的是, perms
在Matlab 6.0之前是遞歸的,然后是非遞歸的,然后又是遞歸的。 因此,除了發明輪子之外,我們還可以采用以前的非遞歸修訂之一,例如1.10
。
請注意,排列順序是不同的,但是無論如何您都不應該依賴於代碼。 您可能需要更改名稱,以避免與本機perms
功能發生沖突。 使用coder.screener
進行了測試,該代碼確認Coder支持它。
function P = perms(V)
%PERMS All possible permutations.
% PERMS(1:N), or PERMS(V) where V is a vector of length N, creates a
% matrix with N! rows and N columns containing all possible
% permutations of the N elements.
%
% This function is only practical for situations where N is less
% than about 10 (for N=11, the output takes over 3 giga-bytes).
%
% See also NCHOOSEK, RANDPERM, PERMUTE.
% ZP. You, 1-18-99
% Copyright 1984-2000 The MathWorks, Inc.
% $Revision: 1.10 $ $Date: 2000/06/16 17:00:47 $
V = V(:)';
n = length(V);
if n == 0
P = [];
else
c = cumprod(1:n);
cn = c(n);
P = V(ones(cn,1),:);
for i = 1:n-1; % for column 1 to n-1, switch oldidx entry with newidx entry
% compute oldidx
j = n-i;
k = (n-j-1)*cn;
oldidx = (c(j)+1+k:c(j+1)+k)';
% spread oldidx and newidx over corresponding rows
for k = j+1:n-1
q = 0:c(k):k*c(k);
shift = q(ones(length(oldidx),1),:);
oldidx = oldidx(:,ones(1,k+1));
oldidx = oldidx(:)+shift(:);
end
% compute newidx
colidx = cn:cn:j*cn;
colidx = colidx(ones(c(j),1),:);
colidx = colidx(:);
colidx = colidx(:,ones(1,length(oldidx)/(j*c(j))));
newidx = oldidx + colidx(:);
% do the swap
q = P(newidx);
P(newidx)=P(oldidx);
P(oldidx)=q;
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.