Subscript indices must either be real positive integers or logicals & Index exceeds matrix dimensions.
1 次查看(过去 30 天)
显示 更早的评论
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?
1 个评论
Jan
2011-10-31
Please use standard code formatting to improve the readability. I've done this for you this time. See "Markup help" on this page.
Do not overwrite the built-in function "sum" by a local variable. This might be working here, but this leads to strange problems frequently.
采纳的回答
Andrei Bobrov
2011-10-31
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
>>
3 个评论
更多回答(3 个)
Amith Kamath
2011-10-31
In MATLAB, unlike in C, the array indices start from 1 and not from 0, and hence all you need to do is to start your loop from 1 instead of 0. The second error is also probably due to this itself, unless the number of elements in P is less than that in C.
0 个评论
Amith Kamath
2011-10-31
Oh you may also want to initialize sum to sum = zeros(size(P)); just so that MATLAB knows that sum has 359 columns, and as a general note, it's always advisable not to name variables the same as functions, for 'sum' happens to be a function too! Hope this fixes it!
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!