Subscript indices must either be real positive integers or logicals & Index exceeds matrix dimensions.
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentar
Jan
am 31 Okt. 2011
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.
Akzeptierte Antwort
Andrei Bobrov
am 31 Okt. 2011
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 Kommentare
Weitere Antworten (3)
Amith Kamath
am 31 Okt. 2011
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 Kommentare
Amith Kamath
am 31 Okt. 2011
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 Kommentare
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!