logo for matrixlab-examples.com
leftimage for matrixlab-examples.com

Matrix Multiplication

If A is a matrix of dimension m x r, and B is a matrix of dimension r x n, you can find the product AB of dimension m x n by doing the following:

1. To find the element in row i and column j of matrix AB, you take row i of matrix A and column j of matrix B.

2. You multiply the corresponding elements of that row and that column and add up all the products.
 



In this example, we show a code in Matlab that performs a matrix multiplication step-by-step. The algorithm displays all the elements being considered for the multiplication and shows how the resulting matrix is being formed in each step. Obviously, Matlab can do it with just one operation (using the ' * ' operator, as in A*B), but we want to show every step of the process, as well as an example of how nested iterations work in Matlab.


Example:


% Clear screen, clear previous variables and closes all figures
clc; close all; clear
% Avoid empty lines
format compact

% Define matrices, for example these
A = [2 1 4 1 2; 1 0 1 2 -1; 2 3 -1 0 -2]
B = [-2 -1 2; 0 2 1; -1 1 4; 3 0 1; 2 1 2]

% The size of each matrix is considered for these calculations
[r1 c1] = size(A);
[r2 c2] = size(B);

% prevent unappropriate matrix size
if c1 ~= r2
    disp ('*** not able to multiply matrices ***')
end

% Main code
% Vary each row of matrix A
for i = 1 : r1
    % Vary each column of matrix B
    for j = 1 : c2
        % Reset every new element of the final result
        s = 0;
        % Vary each column of matrix A and row of matrix B
        for k = 1 : c1
            % Display every element to take into account
            A(i,k)
            B(k,j)
            % Prepare the addition in the iteration
            s = s + A(i,k) * B(k,j);
        end
        % Assign the total of the appropriate element
        % to the final matrix
        C(i,j) = s
    end
end

% Compare our result with a multiplication by Matlab
A*B



Matlab displays the following results:

 A =
     2     1     4     1     2
     1     0     1     2    -1
     2     3    -1     0    -2
B =
    -2    -1     2
     0     2     1
    -1     1     4
     3     0     1
     2     1     2

then, the command window shows all the elements being considered and how the product AB (C) is being formed, and finalizes with our result and the multiplication achieved by Matlab itself.

C =
    -1     6    26
     1    -1     6
    -7     1    -1
ans =
    -1     6    26
     1    -1     6
    -7     1    -1


 From 'Matrix Multiplication' to home

 From 'Matrix Multiplication' to 'Control Flow'
   
Top

Matrix Inversion



footer for matrix multiplication page