MATLAB Answers

error code "Index in position 2 exceeds array bounds (must not exceed 2)."

1 view (last 30 days)
i keep getting this error code, i know something in my matrix must be wrong, also my output must be a matrix
function z = matrix_mult(X,Y)
[x,y]=size(X)
[x1,y1]=size(Y)
for i=1:y % col
for j=1:x1 %row
z(i,j)=X(i,j)*Y(i,j)+X(i,j+1)*Y(i+1,j)
end
end
end
im trying to do matrix multiplication with my own funtion instead of the built in funtion in matlab, i get this first number right and then it pops up with this error

Accepted Answer

Walter Roberson
Walter Roberson on 10 Sep 2020
[x,y]=size(X)
so y will be the number of columns in X.
for i=1:y % col
so the variable referring to columns in X will be i
z(i,j)=X(i,j)*Y(i,j)+X(i,j+1)*Y(i+1,j)
but i is being used as a row index, not as a column index.
Your code does not compute matrix multiplication, unless perhaps your matrices are size 2 (and even then it is likely to get indices out of range.)
For matrix multiplication, z(i,j) should be the sum of the products of row i of X together with the transpose of column j of Y.
  2 Comments
Walter Roberson
Walter Roberson on 10 Sep 2020
Suppose your X is 2 x 3. Then y is going to be 3 because of the way you assigned the output of size(X) . Now you are going to iterate for i = 1 : 3 . You proceed to use X(i,j) . But when i reaches 3, that would be X(3,something) . Which is a problem because X only has 2 rows. The error would then say that you attempted to access past the bounds of the array, stating that the bound was 2. You ran past the end of the array.
You need to pick a variable that will be used to access columns of X and you need to use it to access the columns of X instead of using it to access the rows. You would probably use the same variable to access the rows of Y.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by