I need to create an algorithm in matlab which returns any combination of n subset from the k set.
(我需要在matlab中创建一个算法 ,该算法从k集返回n个子集的任意组合。)
For example I have a set {1,2,3,4,5} and I need any combination of 3 numbers included in this set. (例如,我有一个{1,2,3,4,5}集合,并且需要此集合中包含的3个数字的任意组合。)
So this function should returns: (因此,此函数应返回:)
[[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2, 3, 5], [2, 4, 5], [3, 4, 5]]
([[1、2、3],[1、2、4],[1、2、5],[1、3、4],[1、3、5],[1、4、5],[ 2,3,4],[2,3,5],[2,4,5],[3,4,5]])
I have tried to write it by myself, but unsuccesfully and I give up.
(我试图自己写它,但是没有成功,我放弃了。)
It partially works, but it creates endless loop. (它部分起作用,但会产生无限循环。)
for i=1:n
if(firstTime)
lastComb=min //123
firstTime=false
else
for d=k:-1:1
while(lastComb(:,end) < n-k+d && lastComb(:,end)<=n)
newComb=lastComb
newComb(d)=lastComb(d)+1
combos= [combos; newComb]
lastComb=newComb
end
while(lastComb(:,end) > n-k+d && lastComb(:,end)<=n)
newComb=lastComb
for p=d:-1:1
if(newComb(p)+1 <=n)
newComb(p)=newComb(p)+1
combos= [combos; newComb]
end
end
end
end
end
end
ask by user5890114 translate from so