MATLAB: Subscript indices must either be real positive integers or logicals & Index exceeds matrix dimensions.

index exceeds matrix dimensionssubscript indices must either be real positive integers or logicals.

Hello, the code I'm using is shown below. The file I'm trying to read consists of three columns, two important for me (CA and P). CA has random integer values from 0 to 359 and P has totally random values. I'm trying to do some averages for all the values of 0 to 359.
filename='2000rpm_0R.xlsx'
a=xlsread(filename);
CA=a(:,1);
V=a(:,2);
P=a(:,3);
i=0;
j=0;
sum(i)=0;
for i=0:359
for j=2:size(CA)
if CA(j)==i
sum(i)=sum(i)+P(j);
end
end
end
The error I'm getting is that "??? Subscript indices must either be real positive integers or logicals.
Error in ==> Untitled2 at 10 sum(i)=0;". If i erase the term "sum(i)=0" I get another error that "??? Index exceeds matrix dimensions.
Error in ==> Untitled2 at 18 sum(i)=sum(i)+P(j);"
Any ideas how the problems are solved?

Best Answer

out = [(0:max(CA))',accumarray(CA+1,P,[max(CA)+1,1])]
e.g.
>> CA = randi([0 4],8,1)
CA =
0
0
4
2
2
2
2
1
>> P = randi(12,8,1)
P =
3
11
11
8
5
8
9
11
>> out = [(0:max(CA))',accumarray(CA+1,P,[max(CA)+1,1])]
out =
0 14
1 11
2 30
3 0
4 11
>>
eg averaging
>> out = [(0:max(CA))',accumarray(CA+1,P,[max(CA)+1,1],@mean)]
out =
0 7
1 11
2 7.5
3 0
4 11
>>