Reputation: 1628
Each of my statements work individually, however, I'm having problems with my loop. I have substation data such as this:
1 4
1 5
1 6
2 2
2 8
2 9
3 1
3 5
3 8
I then try to use the following loop to sum the data in the second column grouped by the number in the first column, and then store it in a matrix.
for region = 1:Nnuts3
idx = find(substations(:,1)==Nnuts3);
output = sum(substations(idx,2),1);
mat(Nnuts3,1) = output;
end
Each of the statements in here works fine as an individual line of code when I remove Nnuts3 and place in a number, but it does not work as a whole loop.
What am I doing wrong? I merely want to sum the data using the index in the first row as a condition, and then store the output.
Upvotes: 0
Views: 52
Reputation: 10792
You should use the function accumarray which is specifically designed for your problem:
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)
We obtain:
[[1:max(data(:,1))]',result(:)] =
1 15
2 19
3 14
PS: result = accumarray(data(:,1),data(:,2)) %accumarray(index,data)
will give you the same result, but in my opinion it's more clear to precise the desired "grouping" function.
Upvotes: 3
Reputation: 106
It looks like you were not using the variable region
on the line idx = find(substations(:,1) == region);
The following works for me:
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
Giving the output:
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
I hope that helps :)
Upvotes: 0