เอกสารประกอบการสอน การประมวลผลภาพ ชุดที่ ๗

Page 29

2.4. DEALING WITH MATRICES 36 49

64 9

25 0

25

36 1

Similarly we can produce a matrix of reciprocals by writing 1./a: >> 1./a ans = 0.2500 1.0000 0.1667 -0.1429

-0.5000 0.2000 -0.1250 0.3333

-0.2500 -0.3333 -0.2000 Inf

0.1429 0.5000 -0.1667 1.0000

The value Inf is Matlab’s version of infinity; it is returned for the operation . Operators on matrices Many functions in Matlab, when applied to a matrix, work by applying the function to each element in turn. Such functions are the trigonometric and exponential functions, and logarithms. The use of functions in this way means that in Matlab many iterations and repetitions can be done with vectorization rather than by using loops. We will explore this below.

2.4.3

Constructing matrices

We have seen that we can construct matrices by listing all their elements. However, this can be tedious if the matrix is large, or if it can be generated by a function of its indices. Two special matrices are the matrix consisting of all zeros, and the matrix consisting of all ones. These are generated by the zero and ones functions respectively. Each function can be used in several different ways: zeros(n) zeros(m,n) zeros(m,n,p,...) zeros(a)

if n is a number, will produce a zeros matrix of size if m and n are numbers, will produce a zeros matrix of size where m, n, p and so on are numbers, will produce an multidimensional array of zeros where a is a matrix, will produce a matrix of zeros of the same size as a.

Matrices of random numbers can be produced using the rand and randn functions. They differ in that the numbers produced by rand are taken from a uniform distribution on the interval , and those produced by randn are take from a normal distribution with mean zero and standard deviation one. For creating matrices the syntax of each is the same as the first three options of zeros above. The rand and randn functions on their own produce single numbers taken from the appropriate distribution. We can construct random integer matrices by multiplying the results of rand or randn by an integer and then using the floor function to take the integer part of the result: >> floor(10*rand(3)) ans =


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.