Matlab-求和值等于循环中的条件并存储输出
我的每个语句都是单独工作的,但是,我的循环有问题。我有如下变电站数据:Matlab-求和值等于循环中的条件并存储输出,matlab,loops,sum,conditional-statements,Matlab,Loops,Sum,Conditional Statements,我的每个语句都是单独工作的,但是,我的循环有问题。我有如下变电站数据: 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; e
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并放入一个数字时,这里的每个语句都可以作为单独的代码行正常工作,但它不能作为一个完整的循环工作
我做错了什么?我只想使用第一行中的索引作为条件对数据求和,然后存储输出 看起来您没有在行
idx=find(substations(:,1)=region)上使用变量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
我希望这有帮助:)看起来您没有在线路idx=find(substations(:,1)==region)上使用变量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
我希望这有帮助:)您应该使用专门为您的问题设计的功能:
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(数据(:,1),数据(:,2))%accumarray(索引,数据)
将给出相同的结果,但在我看来,更清楚的是精确地定义所需的“分组”函数。您应该使用专门为您的问题设计的函数:
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(数据(:,1),数据(:,2))%accumarray(索引,数据)
将给出相同的结果,但在我看来,更清楚的是精确地定义所需的“分组”函数。感谢Obchardon,很高兴知道这一点。可能比我想象的循环更有效?谢谢Obchardon,很高兴知道。可能比我想象的循环更有效?