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!