确定大型数据集中的总和
Determine a sum in a large data set
比如说我有数据集
data = [2 4 12.3 54.2 0.3 11 5 3];
我需要找出数据集中哪些变量总和为特定值,例如:8。在这种情况下,这将导致 5 + 3 = 8。
我怎样才能做到这一点?
谢谢
首先,此类问题并不总是有解决方案,而且可能很难找到。
您可能会发现 intlinprog
有用:
n = numel(data);
sumTo = 8; %// the target sum
x = intlinprog(zeros(n,1), 1:n, [], [], data, sumTo, zeros(n,1), ones(n,1));
sel = find(sel);
sel
应包含 data
元素的索引,其总和等于 sumTo
.
即sum(data(sel))==sumTo
.
我认为以下作品。我在列表中添加了三个只是为了更概括一点。
data = [2 4 12.3 54.2 0.3 11 5 3 3];
a=nchoosek(data,2); %all perms
b=sum(a,2);
ii=find(b==8); %find perms summing up to 8
c=nchoosek(1:numel(data),2); %indexes of all perms
d=c(ii,:) %are the indexes
e=data(d) %are the values summing up to 8
d =
7 8
7 9
e =
5 3
5 3
如果您想寻求详尽搜索类型的解决方案(按照 ), you can use perms
提出的思路:
n = numel(data);
sumTo = 8; %// target sum
pidx = perms(1:n); %// indices of all permutations. note the EXPONENTIAL blow
pdata = data(pidx); %// all permutations
csm = cumsum(pdata, 2); %// sum along second dim
[r c] = find(csm == sumTo); %// which perm sum to target sum
if ~isempty(r)
%// select the first solution
sel = pidx(r(1), 1:c(1)); %// sum(data(sel))==8
end
比如说我有数据集
data = [2 4 12.3 54.2 0.3 11 5 3];
我需要找出数据集中哪些变量总和为特定值,例如:8。在这种情况下,这将导致 5 + 3 = 8。
我怎样才能做到这一点?
谢谢
首先,此类问题并不总是有解决方案,而且可能很难找到。
您可能会发现 intlinprog
有用:
n = numel(data);
sumTo = 8; %// the target sum
x = intlinprog(zeros(n,1), 1:n, [], [], data, sumTo, zeros(n,1), ones(n,1));
sel = find(sel);
sel
应包含 data
元素的索引,其总和等于 sumTo
.
即sum(data(sel))==sumTo
.
我认为以下作品。我在列表中添加了三个只是为了更概括一点。
data = [2 4 12.3 54.2 0.3 11 5 3 3];
a=nchoosek(data,2); %all perms
b=sum(a,2);
ii=find(b==8); %find perms summing up to 8
c=nchoosek(1:numel(data),2); %indexes of all perms
d=c(ii,:) %are the indexes
e=data(d) %are the values summing up to 8
d =
7 8
7 9
e =
5 3
5 3
如果您想寻求详尽搜索类型的解决方案(按照 perms
提出的思路:
n = numel(data);
sumTo = 8; %// target sum
pidx = perms(1:n); %// indices of all permutations. note the EXPONENTIAL blow
pdata = data(pidx); %// all permutations
csm = cumsum(pdata, 2); %// sum along second dim
[r c] = find(csm == sumTo); %// which perm sum to target sum
if ~isempty(r)
%// select the first solution
sel = pidx(r(1), 1:c(1)); %// sum(data(sel))==8
end