??? Index Exceeds Matrix Dimensions (NEW TO MATLAB)
Show older comments
I am trying to make the script read through 12 sheets, then calculate the average of 5 numbers (for all 22 subjects, for all 12 sheets), and then write a 22x48 matrix that contains the averages on a new spreadsheet. When I run through the script, I get the index exceeds matrix dimensions message. I am assuming this means that what I specified is too large for the matrix to be written. How do I fix this issue?
% Read in a loop of all 12 sheets
n = 12;
j = 0;
B = [];
for k = 1:n;
A = xlsread('ABC.xls',k);
% Loop for all 22 subjects
c = 0;
for i = 1:22;
B(i,j+1) = (A(5+c,8) + A(6+c,8) + A(7+c,8) + A(10+c,8) + A(11+c,8))/5
B(i,j+2) = (A(25+c,8) + A(26+c,8) + A(27+c,8) + A(21+c,8) + A(22+c,8))/5
B(i,j+3) = (A(7+c,8) + A(8+c,8) + A(11+c,8) + A(12+c,8) + A(17+c,8))/5
B(i,j+4) = (A(4+c,8) + A(5+c,8) + A(9+c,8) + A(10+c,8) + A(15+c,8))/5
c = c + 32;
end
j = j + 4;
k = k + 1;
end
%Write the matrix into a separate excel spreadsheet
xlswrite('ABC Output.xls',B);
1 Comment
Jan
on 27 Mar 2012
Please read the "Markup help" link to learn how to format your code.
Answers (2)
Geoff
on 27 Mar 2012
I would say it's due to the line:
c = c + 32;
The largest row index you have is A(27+c,8). The value of c gets up to '0 + 21*32' = 672 rows. Does A contain at least 672+27 rows? Does A contain at least 8 columns?
Also, don't increment 'k' at the end of the k-loop. It won't do anything, due to the way the for-loop works but it's not a good idea. If you want every second value of k, then loop:
for k = 1:2:n
1 Comment
Christina
on 27 Mar 2012
Jan
on 27 Mar 2012
It is useless and confusing to increase the loop counter inside the loop:
for k = 1:n;
...
k = k + 1; % <- omit this line
end
The best method to solve such problems is the debugger. Type this:
dbstop if error
in the command line (or use the debug menu in the editor accordingly). Then start your program. If an error occurs, Matlab stops and you can inspect the values of the variables in the command window.
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!