但是,我的每个语句都是单独工作的,但是我的循环有问题。我有这样的变电站数据:
1 4
1 5
1 6
2 2
2 8
2 9
3 1
3 5
3 8
然后,我尝试使用下面的循环将第二列中的数据按第一列中的数字分组,然后将其存储在一个矩阵中。
for region = 1:Nnuts3
idx = find(substations(:,1)==Nnuts3);
output = sum(substations(idx,2),1);
mat(Nnuts3,1) = output;
end
当我移除Nnuts3并放入一个数字中时,这里的每个语句都可以作为单独的代码行工作,但是它不能作为一个完整的循环工作。
我做错了什么?我只想将第一行中的索引作为一个条件对数据进行求和,然后存储输出。
发布于 2016-11-29 11:07:53
看起来您没有在行region
上使用变量idx = find(substations(:,1) == region);
。
以下几点对我来说是可行的:
clear all;
substations = [1, 4; 1, 5; 1, 6; 2, 2; 2, 8; 2, 9; 3, 1; 3, 5; 3, 8];
Nnuts3 = 8; % or whatever it needs to be
for region = 1:Nnuts3
idx = find(substations(:,1) == region);
output = sum(substations(idx,2), 1);
mat(region,1) = output;
end
给出输出:
mat =
15.0000e+000
19.0000e+000
14.0000e+000
0.0000e+000
0.0000e+000
0.0000e+000
0.0000e+000
0.0000e+000
我希望这有帮助:)
发布于 2016-11-29 12:04:46
您应该使用针对您的问题而专门设计的函数累加阵列:
data = [1, 4; 1, 5; 1, 6; 2, 2; 2, 8; 2, 9; 3, 1; 3, 5; 3, 8];
result = accumarray(data(:,1),data(:,2),[],@sum) %accumarray(index,data,[],@function)
我们获得:
[[1:max(data(:,1))]',result(:)] =
1 15
2 19
3 14
PS:result = accumarray(data(:,1),data(:,2)) %accumarray(index,data)
会给出同样的结果,但在我看来,更明确的是精确地实现所需的“分组”功能。
https://stackoverflow.com/questions/40863928
复制相似问题