>> a = [1 2 3 ; 4 5 6 ; 7 8 10], b = [1 1 1]'Scalars multiply matrices as expected, and matrices may be added in the usual way; both are done "element by element."
>> 2*a, a/4 >> a + [b,b,b]Scalars added to matrices produce a "strange" result, but one that is sometimes useful; the scalar is added to every element.
>> a+1, b+2Matrix multiplication requires that the sizes match. If they don't, an error message is generated.
>> a*b, b*a >> b'*a >> a*a', a'*a >> b'*b, b*b'To perform an operation on a matrix element-by-element, precede it by a period.
>> a^2, a.^2 >> a.*a, b.*b >> 1 ./ a >> 1./a.^2One of the main uses of matrices is in representing systems of linear equations. If a is a matrix containing the coefficients of a system of linear equations, x is a column vector containing the "unknowns," and b is the column vector of "right-hand sides," the constant terms, then the matrix equation
>> x = a \ bThis can be read "x equals a-inverse times b." To verify this assertion, look at
>> a*x, a*x - bChange b, and do the problem again.
>> b = [1 1 0]' >> x = a\b >> a*x, a*x - bIf there is no solution, a "least-squares" solution is provided [a*x - b is as small as possible]. Enter
>> a(3,3) = 9[which makes the matrix singular] and do those again. [Use the up-arrow, to recall the commands without retyping them].
There is a related problem, to solve x a = b (given a and b), which is done with
>> x = b / aThis can be read "B times A-inverse." Again, if there is no solution, a least-squares solution is found.
There are a number of builtin matrix functions, for example the determinant, rank, nullspace, and condition number.
>> det(a) >> rank(a) >> norm(a) >> null(a)Enter
>> a(3,3) = 10[which makes the matrix nonsingular] and do those again.
Other valuable functions find the inverse, eigenvalues and eigenvectors of a matrix.
>> h=hilb(5) >> cond(a) >> inv(h) >> eig(h)The "eig" function has two forms of output. The last command produced a vector of eigenvalues. The next command produces two matrices, the first containing the eigenvectors as its columns, and the second containing the eigenvalues, along its diagonal.
>> [v,d]=eig(h)The matrix, h, times the first eigenvector, v(:,1), should equal the first eigenvalue, d(1,1), times that same eigenvector.
>> h*v(:,1) >> d(1,1)*v(:,1)"Round-off error" is a primary concern in numerical computing. Matlab does numerical computation, which is to say, it works with limited precision; all decimal expansions are truncated at the sixteenth place [roughly speaking]. Even if this is acceptable for any single calculation, its effects may accumulate with unacceptable consequences. The machine's round-off, the smallest distinguishable difference between two numbers as represented in Matlab, is denoted "eps".
>> help eps >> epsWe can check the assertion just made about eigenvectors and eigenvalues, as follows.
>> h*v(:,1) - d(1,1)*v(:,1)This is "the zero vector, modulo round-off error."