error code "Index in position 2 exceeds array bounds (must not exceed 2)."
조회 수: 5 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
채택된 답변
Walter Roberson
2020년 9월 10일
[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
Walter Roberson
2020년 9월 10일
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!