Index out of bounds for simple nested for loop
Show older comments
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
More Answers (0)
Categories
Find more on Dates and Time 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!