create a for loop that will matrix multiply two 3 by 3 matrices in matlab

Here is an example code snippet that creates two 3 by 3 matrices, A and B, and then uses a for loop to matrix multiply them together to form matrix C.

main.m
% Create 3x3 matrices A and B
A = [1 2 3; 4 5 6; 7 8 9];
B = [9 8 7; 6 5 4; 3 2 1];

% Initialize result matrix C
C = zeros(3,3);

% Matrix multiplication using a for loop
for i = 1:3
    for j = 1:3
        for k = 1:3
            C(i,j) = C(i,j) + A(i,k) * B(k,j);
        end
    end
end

% Display result matrix C
C
320 chars
19 lines

The output of this code will be the following 3 by 3 matrix:

main.m
    30    24    18
    84    69    54
   138   114    90
57 chars
4 lines

Note that Matlab also provides a built-in function for matrix multiplication, A*B, which would produce the same result as the for loop above. However, the for loop approach may be useful in cases where you need more control over the ordering of the multiplication or want to customize the multiplication algorithm beyond what is provided by the built-in function.

gistlibby LogSnag