Professional Documents
Culture Documents
INTRODUCTION
1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 What is MATLAB? Why Matrix The MATLAB System Starting MATLAB on Windows Platforms Quitting MATLAB MATLAB Windows Running Basic Command Scope of MATLAB
Chapter 1: Introduction This is the set of tools and facilities that help you use MATLAB functions and files. Many of these tools are graphical user interfaces. It includes the MATLAB desktop and Command Window, a command history, an editor and debugger, and browsers for viewing help, the workspace, files, and the search path. The MATLAB Mathematical Function Library This is a vast collection of computational algorithms ranging from elementary functions, like sum, sine, cosine, and complex arithmetic, to more sophisticated functions like matrix inverse, matrix eigenvalues, Bessel functions, and fast Fourier transforms. The MATLAB Language This is a high-level matrix/array language with control flow statements, functions, data structures, input/output, and object-oriented programming features. It allows both "programming in the small" to rapidly create quick and dirty throw-away programs, and "programming in the large" to create large and complex application programs. Graphics MATLAB has extensive facilities for displaying vectors and matrices as graphs, as well as annotating and printing these graphs. It includes high-level functions for twodimensional and three-dimensional data visualization, image processing, animation, and presentation graphics. It also includes low-level functions that allow you to fully customize the appearance of graphics as well as to build complete graphical user interfaces on your MATLAB applications. The MATLAB External Interfaces (API) This is a library that allows you to write C and Fortran programs that interact with MATLAB. It includes facilities for calling routines from MATLAB (dynamic linking), calling MATLAB as a computational engine, and for reading and writing MAT-files.
Chapter 1: Introduction
Figure MATLAB Desktop The following illustration shows the default desktop. MATLAB has an extensive graphical user interface. When MATLAB starts, the MATLAB window will appear, with several subwindows and menu bars. All of MATLABs windows in the default desktop are docked, which means that they are tiled on the main MATLAB window. You can undock a window by selecting the menu item Desktop Undock or by clicking its undock button: Help window This window is the most useful window for beginning MATLAB users, and MATLAB experts continue to use it heavily. Select Help MATLAB Help or type doc. The Help window has most of the features you would see in any web browser (clickable links, a back button, and a search engine, for example). You can also use the help command, typed in the Command window. For example, the command help eig will give information about the eigen value function eig. You can also preview some of the features of MATLAB by first entering the command demo or by selecting Help Demos, and then selecting from the options offered. Start button The Start button in the bottom left corner of the MATLAB Desktop allows you to start up demos, tools, and other windows not present when you start MATLAB. Try Start: MATLAB: Demos and run one of the demos from the MATLAB Demo window. Command window
Chapter 1: Introduction MATLAB expressions and statements are evaluated as you type them in the Command window, and results of the computation are displayed there too. Expressions and statements are also used in M-files. They are usually of the form: variable = expression or simply functions Expressions are usually composed from operators, functions, and variable names. Evaluation of the expression produces a matrix (or other data type), which is then displayed on the screen or assigned to a variable for future use. If the variable name and = sign are omitted, a variable ans (for answer) is automatically created to which the result is assigned. A statement is normally terminated at the end of the line. However, a statement can be continued to the next line with three periods (...) at the end of the line. Several statements can be placed on a single line separated by commas or semicolons. Click on the Workspace tab to bring up the Workspace window (it starts out underneath the Current Directory window in the default layout) so you can see a list of the variables you create, and type this command in the Command window: >>A = [1 2 3 ; 4 5 6 ; -1 7 9] or this one: >>A = [ 123 456 -1 7 9] in the Command window. Either one creates the obvious 3-by-3 matrix and assigns it to a variable A. Note: MATLAB is case-sensitive in the names of commands, functions, and variables, so A and a are two different variables. Note: If you want to use reuse previously used command on the command window, it is easier to hit the up arrow key until you see the command you want in the history of MATLAB, and then hit enter. You can clear the Command window with the { >>clc }command or with Edit Clear Command Window. Most numeric computations in MATLAB are done in double precision, which has about 16 digits of accuracy. The command format compact suppresses most blank lines, allowing more information to be placed on the screen or page. The command format loose returns to the non-compact format. These two commands are independent of the other format commands.
Chapter 1: Introduction You can pause the output in the Command window with the { >>more on } command. Type { >>more off } to turn this feature off. Workspace window The Workspace window lists variables that you have either entered or computed in your MATLAB session. There are many fundamental data types (or classes) in MATLAB, each one a basically multidimensional array. An array of this type is called a matrix. A matrix with only one row or one column is called a vector (row vectors and column vectors behave differently; they are more than mere one-dimensional arrays). A 1-by-1 matrix is called a scalar. All the matrices and other variables that you create on the command prompt, are shown in your Workspace window. The command { >>who } or { >>whos } lists the variables currently in the workspace with their properties. A variable can be cleared from the workspace with the command { >>clear variablename } or by rightclicking the variable in the Workspace editor and selecting Delete. The command { >>clear } alone clears all variables from the workspace. Command History window This window lists all the commands used so far. You can re-execute a command from this window by double-clicking or dragging the command into the Command window. Array Editor Window Once an array exists, it can be modified with the Array Editor, which acts like a spreadsheet for matrices. Go to the Workspace window and double-click on the variable. The array editor window will gets opened where you can edit the variable and then go back to the Command window and type the name of variable. Note: You can also edit the variable by typing the command >>openvar('nameVariable') Current Directory window Your current directory is where MATLAB looks for your M-files, and for workspace (.mat) files that you load and save. You can use the menus and buttons in the Current Directory window to peruse your files. The command { >>pwd } returns the name of the current directory, and { >>cd } will change the current directory. The command { >>dir } lists the contents of the current working directory, whereas the command { >>what } lists only the MATLAB-specific files in the directory, and grouped by file type. The MATLAB commands { >>delete } and { >>type } can be used to delete a file and display a file in the Command window, respectively.
Chapter 2
MATLAB KNOW THE BASICS
2.1 Managing Variables 2.2 Accessing Array and Matrix 2.3 The Colon ( : ) Operator Creating Variables 2.4 Suppressing The Output 2.5 Diary 2.6 Storing the Variables and Workspace in MAT File 2.7 Sub-matrices and Colon
2 13 11 8 7 12 14 1
Once you have entered the matrix, it is automatically remembered in the MATLAB workspace. Deleting Rows and Columns You can delete rows and columns from a matrix using just a pair of square brackets. Start with >>X = A; Then, to delete the second column of X, use >>X(:,2) = []
This changes X to X= 16 2 13 5 11 8 9 7 12 4 14 1 If you delete a single element from a matrix, the result is not a matrix anymore. So, expressions like >>X(1,2) = [] result in an error. However, using a single subscript deletes a single element, or sequence of elements, and reshapes the remaining elements into a row vector. So >>X(2:2:10) = [] results in X= 16
13
12
Deleting the variables With the help of { >>clear } one can delete the entire workspace, and also it is possible to delete the particular variable by referring its name in the command.
Chapter 2: MATLAB Know the Basics >>t = A(4,5) Index exceeds matrix dimensions. On the other hand, if you store a value in an element outside of the matrix, the size increases to accommodate the newcomer: >>X = A; >>X(4,5) = 17 X= 16 3 5 10 9 6 4 15
2 13 11 8 7 12 14 1
0 0 0 17
Next, create a column vector, x, with: >>x = [4 5 6]' or equivalently >>x = [3 ; 2 ; 1] With this vector, x(3) denotes the third coordinate of vector x, with a value of 1. Higher dimensional arrays are similarly indexed. An array in the MATLAB accepts only positive integers as index. In an array index expression, end denotes the index of the last element. Try: x = rand(1,5) x = x(end:-1:1)
2.5 Diary
You can save the Command window dialog with the diary command: diary filename This causes what appears subsequently in the Command window to be written to the named file (if the filename is omitted, it is written to a default file named diary) until you type the command diary off; the command diary on causes writing to the file to resume. When finished, you can edit the file as desired and print it out. For hard copy of graphics
10
>>A(:,[2 4 5]) = B(:,1:3) replaces columns 2,4,5 of A with the first three columns of B. Try it. Note that the entire altered matrix A is displayed and assigned. In this way one can create a sub-matrix from any matrix in simple single statement.
11
Chapter 3
MANIPULATING VARIABLES IN MATLAB
3.1 Matrix Operators 3.2 Element-Wise Operators 3.3 Relational Operators and Logical Operators 3.4 Other Data Types 3.5 Basic Built-In Functions
matrix A by adding one to each of its elements: >>A = A + 1 These matrix operators apply, of course, to scalars (1 x 1 matrices) as well. If the sizes of the matrices are incompatible for the matrix operation, an error message will result, except in the case of scalar-matrix operations (for addition, subtraction, division, and multiplication, in which case each entry of the matrix is operated on by the scalar, as in A=A+1). Matrix division (slash and backslash operators) The matrix division operations deserve special comment. These are also called the backslash (\) and slash operators (/); they are also referred to as the mldivide and mrdivide functions. If A is square and non-singular, then A\b and b/A are mathematically the same as inv(A)*b and b*inv(A), respectively, where inv(A) computes the inverse of A.
They all operate entry-wise. Note that = is used in an assignment statement whereas == is a relational operator. Relational operators may be connected by logical operators: & | ~ && || and or not short-circuit and short-circuit or
The result of a relational operator is of type logical, and is either true (one) or false (zero). Thus, ~0 is 1, ~3 is 0, and 4 & 5 is 1, for example. When applied to scalars, the result is a scalar. Try entering 3 < 5, 3 > 5, 3 == 5, and 3 == 3. When applied to matrices of the same size, the result is a matrix of ones and zeros giving the value of the expression between corresponding entries. You can also compare elements of a matrix with a scalar. Test: >>A = [1 2 ; 3 4] >>A >= 2 >>B = [1 3 ; 4 2] >>A < B The short-circuit operator && acts just like its non-shortcircuited counterpart (&), except that it evaluates its left expression first, and does not evaluate the right expression if the first expression is false. This is useful for partially-defined functions. Suppose f(x) returns a logical value but generates an error if x is zero. The expression (x~=0) && f(x) returns false if x is zero, without calling f(x) at all. The short-circuit or (||) acts similarly. It does not evaluate the right expression if the left is true. Both
13
Chapter 3: Manipulating Variables in MATLAB && and || require their operands to be scalar and convertible to logical, while & and | can operate on arrays.
14
Chapter 3: Manipulating Variables in MATLAB magic magic square The command rand(n) creates an n-by-n matrix with randomly generated entries distributed uniformly between 0 and 1 while rand(m,n) creates an m-by-n matrix (m and n are non-negative integers). Try: >>A = rand(3) If x is a vector, diag(x) is the diagonal matrix with x down the diagonal; if A is a matrix, then diag(A) is a vector consisting of the diagonal of A. Try: >>x = 1:3 >>diag(x) >>diag(A) magic(n) creates an n-by-n matrix that is a magic square (rows, columns, and diagonals have common sum) Scalar functions Certain MATLAB functions operate essentially on scalars but operate entry-wise when applied to a vector or matrix. Some of the most common such functions are: abs ceil floor rem sqrt acos cos log round tan asin exp log10 sign atan fix mod sin The following statements will generate a sine table: >>x = (0:0.1:2)' >>y = sin(x) >>plot(x y) Note It produces a vector y from the vector x.
15
Chapter 3: Manipulating Variables in MATLAB Vector functions Most of these functions perform basic statistical computations The primary functions are: max sum median min mean The maximum entry in a matrix A is given by max(A), if A is a row vector. MATLAB functions may have single or multiple output arguments. Square brackets are used to the left of the equal sign to list the outputs. For example, >>[m n] = size(A) produces a column vector containing the count of row and column of a matrix The find function The find function is unlike the other matrix and vector functions. find(x), where x is a vector, returns an array of indices of nonzero entries in x. This is often used in conjunction with relational operators. Suppose you want a vector y that consists of all the values in x greater than 1. >>x = 2*rand(1,5) >>y = x(find(x > 1)) With three output arguments, you get more information: >>A = rand(3) >>[i,j,x] = find(A) returns three vectors, with one entry in i, j, and x for each nonzero in A (row index, column index, and numerical value, respectively). With this matrix A, >>[i,j,x] = find(A > .5)
16
Chapter 4
PROGRAMMING IN MATLAB THE M - FILES
4.1 Basic Parts of an M-File 4.2 Branching 4.3 Loops 4.4 Breaking from a Loop 4.5 Structure of Function M-files
MATLAB provides a full programming language that enables you to write a series of MATLAB statements into a file and then execute them with a single command. You write your program in an ordinary text file, giving the file a name of filename.m. The term you use for filename becomes the new command that MATLAB associates with the program. The file extension of .m makes this a MATLAB M-file. This section covers Types of M-Files Basic Parts of an M-File Creating a Simple MFile. M-files can be scripts that simply execute a series of MATLAB statements, or they can be functions that also accept input arguments and produce output. MATLAB scripts: Are useful for automating a series of steps you need to perform many times. Do not accept input arguments or return output arguments. Store variables in a workspace that is shared with other scripts and with the MATLAB command line interface.
%end of file
Scripts can have any MATLAB Commands. Every time you create an M-file, you are writing a computer program using the MATLAB programming language. You can do quite a lot in MATLAB using no more than the most basic programming techniques that we have already introduced. Here techniques that is useful for attacking more complicated problems with MA TLAB. If
Chapter 4: Programming in MATLAB The M - Files you are already familiar with another programming language, much of this material will be quite easy for you to pick up!
4.2 Branching
In the M-file commands are executes the same sequence as they have written every condition. However, one often wants a function to perform a different sequence of commands in different cases, depending on the conditions. You can accomplish this with a branching command, and as in many other programming languages, branching in MATLAB is usually done with the command if, which we will discuss now. Branching with if For a simple illustration of branching with if, consider the following code M-file, which computes the absolute value of a real number: if x >= 0 y = x; else y = -x; end The first line of this M-file states that the function has a single input x and a single output y. If the input x is nonnegative, the if statement is determined by MATLAB to be true. Then the command between the if and the else statements is executed to set y equal to x, while MATLAB skips the command between the else and end statements. And in the opposite condition the opposite part will be executed. In general, if must be followed on the same line by an expression that MATLAB will test to be true or false. In between, there may be one or more elseif statements (see below) and/or an else statement (as above). Note: that MATLAB requires a double equal sign == to test for equality; a single equal sign is reserved for the assignment of values to variables. Logical Expressions In the examples above, we used relational operators suchas >=, >, and == to form a logical expression, and we instructed MATLAB to choose between different commands according to whether the expression is true or false. Type help relop to see all of the available relational operators. Some of these operators, suchas & (AND) and | (OR), can be used to form logical expressions that are more complicated than those that simply compare two numbers. For example, the expression(x > 0) | (y > 0) will be true if x or y (or both) is positive, and false if neither is positive. In this particular example, the parentheses are not necessary, but generally compound logical expressions like this are both easier to read and less prone to errors if parentheses are used to avoid ambiguities.
18
Chapter 4: Programming in MATLAB The M - Files Branching with switch The other main branching command is switch. It allows you to branch among several cases just as easily as between two cases, though the cases must be described through equalities rather than inequalities. Here is a simple example, which distinguishes between three cases for the input: switch x case 1 y = one; case 2 y = two; otherwise y = many; end Here the switch statement evaluates the input x and then execution of the M-file skips to whichever case statement has the same value. Thus if the input x equals 1, then the output y is set to be the string one, while if x is 2, then y is set to two. In each case , once MATLAB encounters another case statement or since an otherwise statement, it skips to the end statement, so that at most one case is executed. If no match is found among the case statements, then MATLAB skips to the (optional) otherwise statement, or else to the end statement. In the example above, because of the otherwise statement, the output is many if the input is not 1 or 2.
4.3 Loops
Loop a sequence of commands to be executed multiple times. A loop specifies that a command or group of commands should be repeated several times. The easiest way to create a loop is to use a for statement. Here is a simple example that computes and displays 10! = 10 9 8 2 1: f = 1; for n = 2:10 f = f*n; end f The loop begins with the for statement and ends with the end statement. The command between those statements is executed a total of nine times, once for each value of n from 2 to 10. We used a semicolon to suppress intermediate output within the loop. While Loop When you use for, you effectively specify the number of times to run the loop in advance (though this number may depend for instance on the input to a function Mfile). Sometimes you may want to keep running the commands in a loop until a certain condition is met, without deciding in advance on the number of iterations. In MATLAB, the command that allows you to do so is while.
19
Chapter 4: Programming in MATLAB The M - Files Open-Ended Loops Here is a simple example of a script M-file that uses while to numerically stopping only when the condition not satisfied n = 1; while Condition_Expression(n==1) Statemets Do something here so that n not equal to 1 end
20
Chapter 4: Programming in MATLAB The M - Files The table below briefly describes each of these M-file parts. Both functions and scripts can have all of these parts, except for the function definition line which applies to functions only.
Figure Function details Function Definition Line The function definition line informs MATLAB that the M-file contains a function, and specifies the argument calling sequence of the function All MATLAB functions have a function definition line that follows this pattern. Function Arguments. If the function has multiple output values, enclose the output argument list in square brackets. Input arguments, if present, are enclosed in parentheses following the function name. Use commas to separate multiple input or output arguments. Here is the declaration for a function named sphere that has three inputs and three outputs: function [x, y, z] = sphere(theta, phi, rho) If there is no output, leave the output blank function printresults(x) or use empty square brackets: function [] = printresults(x) The variables that you pass to the function do not need to have the same name as those in the function definition line
21
Chapter 5
MATLAB GRAPHICS
5.1 Basic 2-D graphs 5.2 Multiple Plots on the Same Axes 5.3 Multiple plots in a figure: subplot 5.4 3-D plots
The objective of this chapter is to introduce you to MATLABs high-level 2-D and 3D plotting facilities. A picture, it is said, is worth a thousand words. MATLAB has a powerful graphics system for presenting and visualizing data, which is reasonably easy to use.
Figure shows tan plot In the same way one can plot different standard functions Labels Graphs may be labeled with the following statements: gtext(text) writes a string (text) in the graph window. gtext puts a cross-hair in the graph window and waits for a mouse button or keyboard key to be pressed. The cross-hair can be positioned with the mouse or the arrow keys. Note: Text may also be placed on a graph interactively with Tools -> Edit Plot from the figure window. grid adds/removes grid lines to/from the current graph. The grid state may be toggled. text(x, y, text) writes text in the graphics window at the point specified by x and y. If x and y are vectors, the text is written at each point. If the text is an indexed list, successive points are labeled with corresponding rows of the text. title(text)
23
Chapter 5: MATLAB Graphics writes the text as a title on top of the graph. xlabel(horizontal) labels the x-axis. ylabel(vertical) labels the y-axis.
24
plot3 The function plot3 is the 3-D version of plot. The command plot3(x, y, z) draws a 2-D projection of a line in 3-D through the points whose coordinates are the elements of the vectors x, y and z. For example, the command
25
Chapter 5: MATLAB Graphics plot3(rand(1,10), rand(1,10), rand(1,10)) generates 10 random points in 3-D space, and joins them with lines, as shown in Figure
Figure shows the plot Mesh surfaces This drawing is an example of a mesh surface. To see how such surface is drawn, lets take a simpler example, say z =x2 y2. The surface we are after is the one generated by the values of z as we move around the x-y plane. Lets restrict ourselves to part of the first quadrant of this plane, given by 0 x 5, 0 y 5. The first step is to set up the grid in the x-y plane over which the surface is to be plotted. You can use the MATLAB function meshgrid to do it, as follows: [x y] = meshgrid(0:5); This statement sets up two matrices, x and y. (Functions, such as meshgrid, which return more than one output argument, The two matrices in this example are: x= 012345 012345 012345
26
Chapter 5: MATLAB Graphics 012345 012345 012345 y= 000000 111111 222222 333333 444444 555555 The effect of this is that the columns of the matrix x as it is displayed hold the x coordinates of the points in the grid, while the rows of the display of y hold the y coordinates. Recalling the way MATLAB array operations are defined, element by element, this means that the statement z = x.2 - y.2 will correctly generate the surface points: z= 0 1 4 9 16 25 -1 0 3 8 15 24 -4 -3 0 5 12 21 -9 -8 -5 0 7 16 -16 -15 -12 -7 0 9 -25 -24 -21 -16 -9 0 For example, at the grid point (5, 2), z has the value 52 22 =21. Incidentally, you dont need to worry about the exact relationship between grid coordinates and matrix subscripts; this is taken care of by meshgrid. The statement mesh(z) then plots the surface, with mesh lines connecting the points in the surface that lie above grid points. Note that mesh(z) shows the row and column indices (subscripts) of the matrix z on the x and y axes. If you want to see proper values on the x and y axes use mesh(x,y,z). The function mesh draws a surface as a wire frame.
27
Note: There are many other graphics functions are available in the MATLAB one can refer documentation of MATLAB for the other functions and their features.
28
Chapter 6
BEYOND BASICS OF MATLAB
6.1 String 6.2 Audio Processing 6.3 Image Processing
6.1 Strings
Enclosing text in single quotes forms strings with the char data type:
S = 'I love MATLAB'
To include a single quote inside a string, use two of them together, as in:
S = 'Green''s function'
Strings, numeric matrices, and other data types can be displayed with the function disp. Try disp(S) and disp(B).
Input Strings may be entered in response to the input statement in two ways: 1. You can enclose the string in apostrophes when you enter it, or 2. you can use an additional argument s with input, in which case you must not use apostrophes when entering the string, e.g. >> name = input( Enter your surname: , s ); Enter your surname: OReilly Strings are arrays A MATLAB string is actually an array with each element representing one character in the string. For example, if s = Napoleon whos reveals that s is 1-by-8. The statement who/whos will clear this fact. s(8:-1:1) will therefore display the string Napoleon backwards. String functions blanks generates a string of blanks. deblank removes trailing blanks from a string. int2str, num2str
Chapter 6: Beyond Basics of MATLAB convert their numeric arguments to strings. These functions are handy for labeling graphs with text which includes variable numeric values. ischar returns 1 if its argument is a string, and 0 otherwise. lower, upper convert strings to lowercase and uppercase, respectively. See help for a complete list of string-handling functions.
30
Chapter 6: Beyond Basics of MATLAB wavwrite(y,'filename') wavwrite(y,Fs,'filename') wavwrite(y,Fs,N,'filename') Description wavwrite(y,'filename') writes the data stored in the variable y to a WAVE file called filename. The data has a sample rate of 8000 Hz and is assumed to be 16-bit. Each column of the data represents a separate channel. Therefore, stereo data should be specified as a matrix with two columns. Amplitude values outside the range [-1,+1] are clipped prior to writing. wavwrite(y,Fs,'filename') writes the data stored in the variable y to a WAVE file called filename. The data has a sample rate of Fs Hz and is assumed to be 16-bit. Amplitude values outside the range [-1,+1] are clipped prior to writing. wavwrite(y,Fs,N,'filename') writes the data stored in the variable y to a WAVE file called filename. The data has a sample rate of Fs Hz and is N-bit, where N is 8, 16, 24, or 32. For N < 32, amplitude values outside the range [-1,+1] are clipped. wavplay Play recorded sound on PC-based audio output device Syntax wavplay(y,Fs) wavplay(...,'mode') Description wavplay(y,Fs) plays the audio signal stored in the vector y on a PC-based audio output device. You specify the audio signal sampling rate with the integer Fs in samples per second. The default value for Fs is 11025 Hz (samples per second). wavplay supports only 1- or 2-channel (mono or stereo) audio signals. wavplay(...,'mode') specifies how wavplay interacts with the command line, according to the string 'mode'. The string 'mode' can be 'async' (default value): You have immediate access to the command line as soon as the sound begins to play on the audio output device (a nonblocking device call). 'sync': You don't have access to the command line until the sound has finished playing (a blocking device call). The audio signal y can be one of four data types. The number of bits used to quantize and play back each sample depends on the data type. wavrecord Record sound using PC-based audio input device.
31
Chapter 6: Beyond Basics of MATLAB Syntax y = wavrecord(n,Fs) y = wavrecord(...,ch) y = wavrecord(...,'dtype') Description y = wavrecord(n,Fs) records n samples of an audio signal, sampled at a rate of Fs Hz (samples per second). The default value for Fs is 11025 Hz. y = wavrecord(...,ch) uses ch number of input channels from the audio device. ch can be either 1 or 2, for mono or stereo, respectively. The default value for ch is 1. y = wavrecord(...,'dtype') uses the data type specified by the string 'dtype' to record the sound. The string 'dtype' can be one of the following: 'double' (default value), 16 bits/sample 'single', 16 bits/sample 'int16', 16 bits/sample 'uint8', 8 bits/sample Remarks Standard sampling rates for PC-based audio hardware are 8000, 11025, 2250, and 44100 samples per second. Stereo signals are returned as two-column matrices. The first column of a stereo audio matrix corresponds to the left input channel, while the second column corresponds to the right input channel. Examples Record 5 seconds of 16-bit audio sampled at 11025 Hz. Play back the recorded sound using wavplay. Speak into your audio device (or produce your audio signal) while the wavrecord command runs. Fs = 11025; y = wavrecord(5*Fs,Fs,'int16'); wavplay(y,Fs);
This section introduces some basic image processing concepts, including reading and writing images, performing some basic processing activity on an image 1. Read and Display an Image Clear the MATLAB workspace of any variables and close open figure windows. clear, close all To read an image, use the imread command. The example reads one of the sample images included with the Image Processing Toolbox, pout.tif, and stores it in an array named I.
32
Chapter 6: Beyond Basics of MATLAB I = imread('pout.tif'); imread infers from the file that the graphics file format is Tagged Image File Format (TIFF). For the list of supported graphics file formats, see the imread function reference documentation. Now display the image. The toolbox includes image display functions: imshow. imshow is the toolbox's fundamental image display function. This example uses imshow. imshow(I) Note: The Image Appears in the Workspace as a matrix. To see how the imread function stores the image data in the workspace, check the Workspace browser in the MATLAB desktop. The Workspace browser displays information about all the variables you create during a MATLAB session. The imread function returned the image data in the variable I, which is a 291-by-240 element array of uint8 data. MATLAB can store images as uint8, uint16, or double arrays. You can also get information about variables in the workspace by calling the whos command. Improve Image Contrast pout.tif is a somewhat low contrast image. To see the distribution of intensities in pout.tif, you can create a histogram by calling the imhist function. (Precede the call to imhist with the figure command so that the histogram does not overwrite the display of the image I in the current figure window.) figure, imhist(I) Notice how the intensity range is rather narrow. It does not cover the potential range of [0, 255], and is missing the high and low values that would result in good contrast. The toolbox provides several ways to improve the contrast in an image. One way is to call the histeq function to spread the intensity values over the full range of the image, a process called histogram equalization. I2 = histeq(I); Display the new equalized image, I2, in a new figure window. figure, imshow(I2) Equalized Version of pout.tif Call imhist again to create a histogram of the equalized image I2. If you compare the two histograms, the histogram of I2 is more spread out than the histogram of I1. figure, imhist(I2) Write the Image to a Disk File
33
Chapter 6: Beyond Basics of MATLAB To write the newly adjusted image I2 to a disk file, use the imwrite function. If you include the filename extension '.png', the imwrite function writes the image to a file in Portable Network Graphics (PNG) format, but you can specify other formats. imwrite (I2, 'pout2.png'); See the imwrite function reference page for a list of file formats it supports. Other Basic Image Processing functions im2bw rgb2gray uint16 uint8 imnoise Convert image to binary image by thresholding Convert RGB image or colormap to grayscaler Convert data to unsigned 16-bit integers (MATLAB function) Convert data to unsigned 8-bit integers (MATLAB function) Add noise to an image
34