【发布时间】:2015-03-06 19:18:45
【问题描述】:
是否有更有效的方法来生成范围为 1 到 N 的 X 个二进制数(具有 n 个非零数字)?我开发了以下解决方案:
Totalcombos = nchoosek(N,n);
floor = floor(log2(Totalcombos));
L = 2.^floor;
NumElem = 2^N-1;
i=0;
x=1;
%Creates Index combination LUT
while 1
%Produces Binary from 1 : NumElem
binNum= de2bi(x,N,'right-msb')';
x=x+1;
%Finds number of bits in each binary number
NumOfBits = sum(binNum);
%Creates a matrix of binary numbers from 1:NumElem with n 1's
if NumOfBits == n
i=i+1;
ISmatrixShapes{i} = binNum(:,:);
end
if i==L
break
end
end
ISmatrixShape2=cell2mat(ISmatrixShapes);
ISmatrixShape=ISmatrixShape2(:,1:L)';
有没有一种方法可以在不进行大量循环迭代的情况下生成这些值?
【问题讨论】:
-
提醒一下:
floor = floor(..)不是好习惯