Index out of bounds for simple nested for loop

Hi everybody,
This function works fine when I input P and Q as matrices with equal number of rows and columns but not when they are different sizes (for example, P = [1 2 3 4; 5 6 7 8] and Q = [ 1 1 1; 2 2 2; 3 3 3; 4 4 4].
Can someone point me in the right direction as to what I can fix so that this function will work properly? Thanks.
function [M] = myMatMult (P, Q)
% function that multiplies matrices P and Q
[nRow, nCol] = size(P);
[nRow_1, nCol_1] = size (Q);
if nCol ~= nRow_1
disp 'error';
end
M = zeros(nRow, nCol_1);
for i = 1:nRow
for j = 1:nCol_1
for k = 1: nCol
M(i,j) = M(i, j) + P(i,k)* Q(j,k);
end
end
end
end

 Accepted Answer

Allie - since you are performing your own version of matrix multiplication, if you are multiplying P*Q, then the number of columns in P must be identical to the number of rows in Q.
Now consider your multiplication step
M(i,j) = M(i, j) + P(i,k)* Q(j,k);
where i is from 1 to the number of rows in P, j is from 1 to the number of columns in Q, and k is from one to the number of columns in P. Both i and k are fine for indexing into P but look at the indexing into Q: we use j to access a row, and k to access a column when it should be the other way around! Since the number of columns in Q is equal to the number of rows in P and k is from one to the number of columns in P, we must use k to access a row of Q. So just change this line of code to
M(i,j) = M(i, j) + P(i,k)* Q(k,j);
and you should be good to continue.

2 Comments

Thank you Geoff! That did the trick.
Glad it worked out!

Sign in to comment.

More Answers (0)

Categories

Asked:

on 26 Sep 2014

Commented:

on 26 Sep 2014

Community Treasure Hunt

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

Start Hunting!