% open a file to write in the LaTeX commands:
f = fopen( 'matrices.tex','w');
fprintf( f, '\\documentclass{exam}\n' );
fprintf( f, '\\usepackage{amsmath}\n' );
fprintf( f, '\\begin{document}\n' );

for k = 1:40

    % compute row and column numbers:
    pd = rand( 1, 1 );
    if pd < 0.05
        % row vector multiplication that might not be possible:
        am = 1;
        an = randi( [ 2 4 ]);
        bm = randi( [ 2 4 ]);
        bn = 1;
    elseif pd < 0.1
        % column vector multiplication that might not be possible:
        am = randi( [ 2 4 ]);
        an = 1;
        bm = 1;
        bn = randi( [ 2 4 ]);
    elseif pd < 0.4
        % row vector multiplication that is possible:
        am = 1;
        an = randi( [ 2 4 ]);
        bm = an;
        bn = 1;
    elseif pd < 0.5
        % column vector multiplication that is possible:
        am = randi( [ 2 4 ]);
        an = 1;
        bm = 1;
        bn = am;
    elseif pd < 0.6
        % matrix multiplication that might not be possible:
        am = randi( [ 2 4 ]);
        an = randi( [ 2 4 ]);
        bm = randi( [ 2 4 ]);
        bn = randi( [ 2 4 ]);
    else
        % matrix multiplication that is possible:
        am = randi( [ 2 4 ]);
        an = randi( [ 2 4 ]);
        bm = an;
        bn = randi( [ 2 4 ]);
    end
    % generate the matrices:
    a = randi( [-4 4], am, an );
    b = randi( [-4 4], bm, bn );
    % write them out as LaTeX code:
    %   matrix a:
    fprintf( f, '  \\[ \\begin{pmatrix}' );
    for r = 1:size( a, 1 )
        for c = 1:size( a, 2 )
            if c > 1
                fprintf( f, ' &' );
            end
            fprintf( f, ' %d', a(r,c) );
        end
        if r < size( a, 1 )
            fprintf( f, ' \\\\' );
        end
    end
    fprintf( f, ' \\end{pmatrix} \\cdot\n' );
    %   matrix b:
    fprintf( f, ' \\begin{pmatrix}' );
    for r = 1:size( b, 1 )
        for c = 1:size( b, 2 )
            if c > 1
                fprintf( f, ' &' );
            end
            fprintf( f, ' %d', b(r,c) );
        end
        if r < size( b, 1 )
            fprintf( f, ' \\\\' );
        end
    end
    fprintf( f, ' \\end{pmatrix} = \\]\n\n' );

end

% close the document and the file:
fprintf( f, '\\end{document}\n' );
fclose( f );