Numerical Analysis Lab Note #4 Related Functions and Logical Operators in Matlab

CONTENTS 1. Matrix Generating Functions

2. Matrix Related Function

3. Logical Operators

======1. Matrix Generating Functions:

ONES(N,M), ZEROS(N,M), EYE(N), RAND(N,M), MAGIC(N), PASCAL(N), HILB(N), TOEPLITZ, HANKEL, KRON.

>> help ones ONES Ones array. ONES(N) is an N-by-N matrix of ones.

ONES(M,N) or ONES([M,N]) is an M-by-N matrix of ones.

ONES(M,N,P,...) or ONES([M N P ...]) is an M-by-N-by-P-by-... array of ones.

ONES(SIZE(A)) is the same size as A and all ones.

ONES with no arguments is the scalar 1.

ONES(M,N,...,CLASSNAME) or ONES([M,N,...],CLASSNAME) is an M-by-N-by-... array of ones of class CLASSNAME.

Note: The size inputs M, N, and P... should be nonnegative integers. Negative integers are treated as 0.

Example: x = ones(2,3,’int8’);

1 >> help zeros ZEROS Zeros array. ZEROS(N) is an N-by-N matrix of zeros.

ZEROS(M,N) or ZEROS([M,N]) is an M-by-N matrix of zeros.

ZEROS(M,N,P,...) or ZEROS([M N P ...]) is an M-by-N-by-P-by-... array of zeros.

ZEROS(SIZE(A)) is the same size as A and all zeros.

ZEROS with no arguments is the scalar 0.

ZEROS(M,N,...,CLASSNAME) or ZEROS([M,N,...],CLASSNAME) is an M-by-N-by-... array of zeros of class CLASSNAME.

Note: The size inputs M, N, and P... should be nonnegative integers. Negative integers are treated as 0.

Example: x = zeros(2,3,’int8’);

>> help eye EYE . EYE(N) is the N-by-N identity matrix.

EYE(M,N) or EYE([M,N]) is an M-by-N matrix with 1’s on the diagonal and zeros elsewhere.

EYE(SIZE(A)) is the same size as A.

EYE with no arguments is the scalar 1.

EYE(M,N,CLASSNAME) or EYE([M,N],CLASSNAME) is an M-by-N matrix with 1’s of class CLASSNAME on the diagonal and zeros elsewhere.

Note: The size inputs M and N should be nonnegative integers. Negative integers are treated as 0.

Example: x = eye(2,3,’int8’);

>> help rand RAND Uniformly distributed pseudorandom numbers. R = RAND(N) returns an N-by-N matrix containing pseudorandom values drawn from the standard uniform distribution on the open interval(0,1). RAND(M,N) or RAND([M,N]) returns an M-by-N matrix. RAND(M,N,P,...) or RAND([M,N,P,...]) returns an M-by-N-by-P-by-... array. RAND returns a scalar. RAND(SIZE(A)) returns an array the same size as A.

2 Note: The size inputs M, N, P, ... should be nonnegative integers. Negative integers are treated as 0.

R = RAND(..., ’double’) or R = RAND(..., ’single’) returns an array of uniform values of the specified class.

Examples:

Generate values from the uniform distribution on the interval [a, b]. r = a + (b-a).*rand(100,1);

Generate integer values from the uniform distribution on the set 1:n. r = randi(100,1);

Save the current state of the default stream, generate 5 values, restore the state, and repeat the sequence. defaultStream = RandStream.getDefaultStream; savedState = defaultStream.State; u1 = rand(1,5) defaultStream.State = savedState; u2 = rand(1,5) % contains exactly the same values as u1

Replace the default stream with a stream whose seed is based on CLOCK, so RAND will return different values in different MATLAB sessions. NOTE: It is usually not desirable to do this more than once per MATLAB session. RandStream.setDefaultStream(RandStream(’mt19937ar’,’seed’,sum(100*clock))); rand(1,5)

>> help magic MAGIC Magic square. MAGIC(N) is an N-by-N matrix constructed from the integers 1 through N^2 with equal row, column, and diagonal sums. Produces valid magic squares for all N > 0 except N = 2.

>> magic(4) ans =

16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1

>> help pascal PASCAL . PASCAL(N) is the Pascal matrix of order N: a symmetric positive with integer entries, made up from Pascal’s triangle. Its inverse has integer entries.

3 PASCAL(N).^r is symmetric positive semidefinite for all nonnegative r.

PASCAL(N,1) is the lower triangular Cholesky factor (up to signs of columns) of the Pascal matrix. It is involutory (is its own inverse).

PASCAL(N,2) is a rotated version of PASCAL(N,1), with sign flipped if N is even, which is a cube root of the identity.

PASCAL(N,CLASSNAME) or PASCAL(N,K,CLASSNAME) produces a matrix of class CLASSNAME. CLASSNAME must be either ’single’ or ’double’ (the default).

Reference page in Help browser doc pascal

>> pascal(3) ans =

1 1 1 1 2 3 1 3 6

>> pascal(5) ans =

1 1 1 1 1 1 2 3 4 5 1 3 6 10 15 1 4 10 20 35 1 5 15 35 70

>> help hilb HILB . HILB(N) is the N by N matrix with elements 1/(i+j-1), which is a famous example of a badly conditioned matrix. See INVHILB for the exact inverse.

HILB(N,CLASSNAME) produces a matrix of class CLASSNAME. CLASSNAME must be either ’single’ or ’double’ (the default).

This is also a good example of efficient MATLAB programming style where conventional FOR or DO loops are replaced by vectorized statements. This approach is faster, but uses more storage.

4 See also invhilb.

Reference page in Help browser doc hilb

>> hilb(3) ans =

1.0000 0.5000 0.3333 0.5000 0.3333 0.2500 0.3333 0.2500 0.2000

EXERCISE: >> help toeplitz

>> help hankel

>> help kron

======2. Matrix Related Functions:

SIZE, LENGTH, DET, , EIG, COND, NORM

SUM, DIFF, PROD.

MAX, MIN, ABS.

>> help size SIZE Size of array. D = SIZE(X), for M-by-N matrix X, returns the two-element row vector D = [M,N] containing the number of rows and columns in the matrix. For N-D arrays, SIZE(X) returns a 1-by-N vector of dimension lengths. Trailing singleton dimensions are ignored.

[M,N] = SIZE(X) for matrix X, returns the number of rows and columns in X as separate output variables.

[M1,M2,M3,...,MN] = SIZE(X) for N>1 returns the sizes of the first N dimensions of the array X. If the number of output arguments N does not equal NDIMS(X), then for:

N > NDIMS(X), SIZE returns ones in the "extra" variables, i.e., outputs NDIMS(X)+1 through N. N < NDIMS(X), MN contains the product of the sizes of dimensions N

5 through NDIMS(X).

M = SIZE(X,DIM) returns the length of the dimension specified by the scalar DIM. For example, SIZE(X,1) returns the number of rows. If DIM > NDIMS(X), M will be 1.

When SIZE is applied to a Java array, the number of rows returned is the length of the Java array and the number of columns is always 1. When SIZE is applied to a Java array of arrays, the result describes only the top level array in the array of arrays.

Example: If X = rand(2,3,4); then d = size(X) returns d = [2 3 4] [m1,m2,m3,m4] = size(X) returns m1 = 2, m2 = 3, m3 = 4, m4 = 1 [m,n] = size(X) returns m = 2, n = 12 m2 = size(X,2) returns m2 = 3

See also length, ndims, numel.

>>help length LENGTH Length of vector. LENGTH(X) returns the length of vector X. It is equivalent to MAX(SIZE(X)) for non-empty arrays and 0 for empty ones.

>> help det DET . DET(X) is the determinant of the square matrix X.

Use COND instead of DET to test for matrix singularity.

See also cond.

>> help rank RANK Matrix rank. RANK(A) provides an estimate of the number of linearly independent rows or columns of a matrix A. RANK(A,tol) is the number of singular values of A that are larger than tol. RANK(A) uses the default tol = max(size(A)) * eps(norm(A)).

Class support for input A: float: double, single

>> help eig

6 EIG Eigenvalues and eigenvectors. E = EIG(X) is a vector containing the eigenvalues of a square matrix X.

[V,D] = EIG(X) produces a D of eigenvalues and a full matrix V whose columns are the corresponding eigenvectors so that X*V = V*D.

[V,D] = EIG(X,’nobalance’) performs the computation with balancing disabled, which sometimes gives more accurate results for certain problems with unusual scaling. If X is symmetric, EIG(X,’nobalance’) is ignored since X is already balanced.

E = EIG(A,B) is a vector containing the generalized eigenvalues of square matrices A and B.

[V,D] = EIG(A,B) produces a diagonal matrix D of generalized eigenvalues and a full matrix V whose columns are the corresponding eigenvectors so that A*V = B*V*D.

EIG(A,B,’chol’) is the same as EIG(A,B) for symmetric A and symmetric positive definite B. It computes the generalized eigenvalues of A and B using the Cholesky factorization of B. EIG(A,B,’qz’) ignores the symmetry of A and B and uses the QZ algorithm. In general, the two algorithms return the same result, however using the QZ algorithm may be more stable for certain problems. The flag is ignored when A and B are not symmetric.

See also condeig, eigs, ordeig.

>> help norm NORM Matrix or vector norm. For matrices... NORM(X) is the largest singular value of X, max(svd(X)). NORM(X,2) is the same as NORM(X). NORM(X,1) is the 1-norm of X, the largest column sum, = max(sum(abs(X))). NORM(X,inf) is the infinity norm of X, the largest row sum, = max(sum(abs(X’))). NORM(X,’fro’) is the Frobenius norm, sqrt(sum(diag(X’*X))). NORM(X,P) is available for matrix X only if P is 1, 2, inf or ’fro’.

For vectors... NORM(V,P) = sum(abs(V).^P)^(1/P). NORM(V) = norm(V,2). NORM(V,inf) = max(abs(V)). NORM(V,-inf) = min(abs(V)).

See also cond, rcond, condest, normest, hypot.

7 >> help sum SUM Sum of elements. S = SUM(X) is the sum of the elements of the vector X. If X is a matrix, S is a row vector with the sum over each column. For N-D arrays, SUM(X) operates along the first non-singleton dimension. If X is floating point, that is double or single, S is accumulated natively, that is in the same class as X, and S has the same class as X. If X is not floating point, S is accumulated in double and S has class double.

S = SUM(X,DIM) sums along the dimension DIM.

S = SUM(X,’double’) and S = SUM(X,DIM,’double’) accumulate S in double and S has class double, even if X is single.

S = SUM(X,’native’) and S = SUM(X,DIM,’native’) accumulate S natively and S has the same class as X.

Examples: If X = [0 1 2 3 4 5]

then sum(X,1) is [3 5 7] and sum(X,2) is [ 3 12];

If X = int8(1:20) then sum(X) accumulates in double and the result is double(210) while sum(X,’native’) accumulates in int8, but overflows and saturates to int8(127).

See also prod, cumsum, diff, accumarray, isfloat.

>> help diff DIFF Difference and approximate derivative. DIFF(X), for a vector X, is [X(2)-X(1) X(3)-X(2) ... X(n)-X(n-1)]. DIFF(X), for a matrix X, is the matrix of row differences, [X(2:n,:) - X(1:n-1,:)]. DIFF(X), for an N-D array X, is the difference along the first non-singleton dimension of X. DIFF(X,N) is the N-th order difference along the first non-singleton dimension (denote it by DIM). If N >= size(X,DIM), DIFF takes successive differences along the next non-singleton dimension. DIFF(X,N,DIM) is the Nth difference function along dimension DIM. If N >= size(X,DIM), DIFF returns an empty array.

Examples:

8 h = .001; x = 0:h:pi; diff(sin(x.^2))/h is an approximation to 2*cos(x.^2).*x diff((1:10).^2) is 3:2:19

If X = [3 7 5 0 9 2] then diff(X,1,1) is [-3 2 -3], diff(X,1,2) is [4 -2 9 -7], diff(X,2,2) is the 2nd order difference along the dimension 2, and diff(X,3,2) is the empty matrix.

See also gradient, sum, prod.

>> help prod PROD Product of elements. For vectors, PROD(X) is the product of the elements of X. For matrices, PROD(X) is a row vector with the product over each column. For N-D arrays, PROD(X) operates on the first non-singleton dimension.

PROD(X,DIM) works along the dimension DIM.

Example: If X = [0 1 2 3 4 5]

then prod(X,1) is [0 4 10] and prod(X,2) is [ 0 60]

See also sum, cumprod, diff.

>> help max MAX Largest component. For vectors, MAX(X) is the largest element in X. For matrices, MAX(X) is a row vector containing the maximum element from each column. For N-D arrays, MAX(X) operates along the first non-singleton dimension.

[Y,I] = MAX(X) returns the indices of the maximum values in vector I. If the values along the first non-singleton dimension contain more than one maximal element, the index of the first one is returned.

MAX(X,Y) returns an array the same size as X and Y with the largest elements taken from X or Y. Either one can be a scalar.

[Y,I] = MAX(X,[],DIM) operates along the dimension DIM.

When X is complex, the maximum is computed using the magnitude MAX(ABS(X)). In the case of equal magnitude elements, then the phase angle MAX(ANGLE(X)) is used.

9 NaN’s are ignored when computing the maximum. When all elements in X are NaN’s, then the first one is returned as the maximum.

Example: If X = [2 8 4 then max(X,[],1) is [7 8 9], 7 3 9] max(X,[],2) is [8 and max(X,5) is [5 8 5 9], 7 5 9].

See also min, median, mean, sort.

>> help min MIN Smallest component. For vectors, MIN(X) is the smallest element in X. For matrices, MIN(X) is a row vector containing the minimum element from each column. For N-D arrays, MIN(X) operates along the first non-singleton dimension.

[Y,I] = MIN(X) returns the indices of the minimum values in vector I. If the values along the first non-singleton dimension contain more than one minimal element, the index of the first one is returned.

MIN(X,Y) returns an array the same size as X and Y with the smallest elements taken from X or Y. Either one can be a scalar.

[Y,I] = MIN(X,[],DIM) operates along the dimension DIM.

When X is complex, the minimum is computed using the magnitude MIN(ABS(X)). In the case of equal magnitude elements, then the phase angle MIN(ANGLE(X)) is used.

NaN’s are ignored when computing the minimum. When all elements in X are NaN’s, then the first one is returned as the minimum.

Example: If X = [2 8 4 then min(X,[],1) is [2 3 4], 7 3 9]

min(X,[],2) is [2 and min(X,5) is [2 5 4 3], 5 3 5].

See also max, median, mean, sort.

>> help abs ABS Absolute value. ABS(X) is the absolute value of the elements of X. When X is complex, ABS(X) is the complex modulus (magnitude) of the elements of X.

See also sign, angle, unwrap, hypot.

10 ======3. Logical Operators

< > Relational operators. The six relational operators are <, <=, >, >=, ==, and ~=. A < B does element by element comparisons between A and B and returns a matrix of the same size with elements set to logical 1 (TRUE) where the is true and elements set to logical 0 (FALSE) where it is not. A and B must have the same dimensions (or one can be a scalar).

& Element-wise Logical AND. A & B is a matrix whose elements are logical 1 (TRUE) where both A and B have non-zero elements, and logical 0 (FALSE) where either has a zero element. A and B must have the same dimensions (or one can be a scalar).

&& Short-Circuit Logical AND. A && B is a scalar value that is the logical AND of scalar A and B. This is a "short-circuit" operation in that MATLAB evaluates B only if the result is not fully determined by A. For example, if A equals 0, then the entire expression evaluates to logical 0 (FALSE), regard- less of the value of B. Under these circumstances, there is no need to evaluate B because the result is already known.

| Element-wise Logical OR. A | B is a matrix whose elements are logical 1 (TRUE) where either A or B has a non-zero element, and logical 0 (FALSE) where both have zero elements. A and B must have the same dimensions (or one can be a scalar).

|| Short-Circuit Logical OR. A || B is a scalar value that is the logical OR of scalar A and B. This is a "short-circuit" operation in that MATLAB evaluates B only if the result is not fully determined by A. For example, if A equals 1, then the entire expression evaluates to logical 1 (TRUE), regard- less of the value of B. Under these circumstances, there is no need to evaluate B because the result is already known.

~ Logical complement (NOT). ~A is a matrix whose elements are logical 1 (TRUE) where A has zero elements, and logical 0 (FALSE) where A has non-zero elements.

xor Exclusive OR. xor(A,B) is logical 1 (TRUE) where either A or B, but not both, is non-zero. See XOR.

11