【发布时间】:2019-12-01 12:50:16
【问题描述】:
我需要在 matlab 中创建一个algorithm,它返回 k 集中 n 个子集的任意组合。例如,我有一个集合 {1,2,3,4,5},我需要包含在这个集合中的 3 个数字的任意组合。所以这个函数应该返回:
[[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]]
我曾尝试自己写,但没有成功,我放弃了。它部分有效,但会造成无限循环。
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
【问题讨论】:
-
//不是有效的 MATLAB 语法。你确定你在这里运行代码吗?还请包括变量的初始化。您需要复制粘贴我们可以运行的完整代码。见minimal reproducible example。 -
如果您需要的只是一个可以完成您可以使用的工作的函数:
nchoosek -
你试过
nchoosek(1:5,3)吗?
标签: matlab combinations