TDDD34 Programming with Applications in Engineering
Matrixes in Matlab
This describes commands that manipulate matrixes in different ways. Observe that a vector in Matlab is really a one dimensional matrix (just one row).
Functions and operators
: Generate a vector. For example 1:5 generates the vector [1 2 3 4 5]. If three values is given the middle is interpreted as stride. For example 1:2:6 generate the vector [1 3 5]. If given in place of an index it denotes the entire row/column. Let for example A = [1 2; 3 4] then A(:,2) denote the column [2;4]. .* Perform element by element multiplication. ./ Perform element by element division. .^ Perform element by element exponentiation. ' (apostrophe) Transpose a matrix. find Return a vector with the indexes where the matrix elements are nonzero all Controls if all elements of the matrix are nonzero. any Controls if at least one element in the matrix is nonzero. size Returns the dimension of a matrix (the result is a vector). length Returns the length of a vector or the length of the longest side in a matrix (thus a 2x3-matrix and a 3x2-matrix both yield 3) numel Returns the number of elements in the entire matrix or vector. eye Generate a matrix with ones in the diagonal and zeros elsewhere. ones Generates a vector filled with ones. zeros Generates a vector filled with zeros. diag Generate a matrix with the diagonal set to the argument vector. For example diag([1 1 1]) is the same as eye(3,3). Returns the diagonal elements in the argument matrix. For example diag(eye(3,3)) returns a vector with three ones. fliplr Flips a matrix in left/right direction. flipud Flips a matrix in up/down direction reshape Generates a m*n matrix from a vector with m times n elements. A(r, c) Retrieves the element at position (r, c) where r is the row and c the column. A(2:5, 3:4) Retrieve the submatrix limited by the corners at A(2,3), A(2,4), A(5,3), A(5,4). (I.e. retrieve the matrix created from intersection of rows 2,3,4,5 and columns 3,4.)
You may want to pay attention to the fact that many functions in Matlab accepts matrixes as arguments, even if you normally expect them to handle only ordinary numbers. The function is then performed separately on each element (in the general case). For example "sin" and "abs".
Page responsible: Erik Nilsson
Last updated: 2012-08-07