Sha*_*Sha 2 c++ matlab permutation matlab-coder perms
我试图使用编码器将我在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
Run Code Online (Sandbox Code Playgroud)
对于8个元素,我必须编写8个for循环,有关如何为n个元素转换它的任何建议吗?就像是
for i=n:-1:1
I=[1:n] ;
for j=1:i
J=I(find(I~=j));
... ?
thank you
Run Code Online (Sandbox Code Playgroud)
这里的问题是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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
181 次 |
| 最近记录: |