% simple MATLAB script
format compact
% these commands will print output to the screen
% (there is no ; at the end)
A = [ 1,2 ; 3,4 ; 5,6 ]
B = [ 7,2 ; -1,2 ]
% try the following instead
% B = [ 7,2 ; -1,2 ; 3,4]
% commands that end with a ; do not output to the screen
% 'size' is a function whose output is a list of 2 items
[aRows,aCols] = size(A);
[bRows,bCols] = size(B);
if aCols ~= bRows % remember ~= means "is not equal to"
error('either A or B is the wrong size')
end
% we are going to compute C=AB, first work out its size
cRows = aRows;
cCols = bCols;
% initialise C to all zeros
C = zeros( cRows,cCols );
% double loop over the elements of C
for i = 1:cRows
for j = 1:cCols
% this is the sum required to compute C(i,j)
for k = 1:aCols
C(i,j) = C(i,j) + A(i,k)*B(k,j);
end
end
end
display(C)
% of course MATLAB already knows how to multiply matrices,
% we can use this as a check
display(A*B)