MATLAB: How to improve/debug the matrix-column multiplier

homeworkmatrix multiplication

The idea here is to multiply matrix A with column B in a function file. The assignment is: "Make a function file of the following form:
function D = matmult(A,B)
that multiplies matrices A and B of arbitrary dimensions. Do this by using only the scalar multiplying operator `*'. In other words, write a matrix multiplication such that only (multiple times after each other) two normal numbers are multiplied." "Fill the resulting matrix, element after element, with a for-loop. The value of each element is a summation of different product terms (an inner-product). For this a new for-loop needs to be implemented in the first for-loop with the following assignment instruction:
sum = sum + change (the new value of the sum becomes the previous value of the sum plus the value of the change)
A possible example is given below >> A = [3 4;6 1]; >> B = [1 3]'; >> D = matmult(A,B) where the answer becomes D = [15 9]'
The code I made is almost there. The only bit I am confused about is how to improve the lines from 'sum = 0;' on.
function D = matmult(A,B)
[a,b] = size(A);
[c,d] = size(B);
if b==c
disp('match of matrix sizes');
D = zeros(a,d);
else
error('mismatch of matrix sizes');
end
sum = 0;
for j = 1:d
for i = 1:a
change = A(i,j)'.*B(i,j);
sum = sum + change;
end
end
D = [sum sum]';

Best Answer

Your example is a standard matrix multiply, and your attempt is not too far off, so I will provide some corrections with some other comments where you will need to complete the code (assuming your instructor wants to use a loop for the element sum as seems to be indicated from your description):
D = zeros(a,d); % Pre-allocate the result
for j = 1:d
for i = 1:a
sum = 0; % Move this line inside the for loops, each element sum starts at 0
for k=1:b % The "sigma" loop as shown in the Wiki link above
change = CODE FOR YOU TO FILL IN GOES HERE; % See Wiki link
sum = sum + change; % Incrementally sum up the changes for the (i,j) element
end
D(i,j) = sum; % Store the result for the (i,j) element
end
end
Pay particular attention to the indexing used for the "sigma" loop in the Wiki link.
https://en.wikipedia.org/wiki/Matrix_multiplication