Fundamentals Of Matlab Programming


Published on

  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Fundamentals Of Matlab Programming

  1. 1. Delivered by A. K. Bhattacharyya Senior Project Assistant Department of Electrical Engineering IIT Kharagpur Matlab Programming
  2. 2. The m file <ul><li>Write a series of MATLAB statements into a file and then execute them with a single command. </li></ul><ul><li>Write your program in an ordinary text editor (Notepad), 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 . </li></ul>
  3. 3. Kinds of M files Useful for extending the MATLAB language for your application Useful for automating a series of steps you need to perform many times Internal variables are local to the function by default Operate on data in the workspace Can accept input arguments and return output arguments Do not accept input arguments or return output arguments Function M-Files Script M-Files
  4. 4. An example of a script m-file Factorial.m n=10; factorial=1; for i=1:1:n factorial=factorial*i; end
  5. 5. An example of a function m-file Comment defines the function name, and the number and order of input and output parameters H1 stands for &quot;help 1&quot; line. MATLAB displays the H1 line for a function when you use lookfor or request help on an entire directory.
  6. 6. Creating M-Files: Accessing Text Editors <ul><li>edit fact .m </li></ul>
  7. 7. Listing files <ul><li>List the names of the files in your current directory: what </li></ul>
  8. 8. Checking file content <ul><li>List the contents of M-file fact.m: type fact </li></ul>
  9. 9. Calling function <ul><li>Call the fact function: fact(5) </li></ul>
  10. 10. Variables <ul><li>The same guidelines that apply to MATLAB variables at the command line also apply to variables in M-files: </li></ul><ul><li>No need to type or declare variables used in M-files, (with the possible exception of designating them as global or persistent ). </li></ul>
  11. 11. Variables <ul><li>Before assigning one variable to another, you must be sure that the variable on the right-hand side of the assignment has a value. </li></ul><ul><li>Any operation that assigns a value to a variable creates the variable, if needed, or overwrites its current value, if it already exists. </li></ul>
  12. 12. Variables <ul><li>MATLAB variable names must begin with a letter, which may be followed by any combination of letters, digits, and underscores. </li></ul><ul><li>MATLAB distinguishes between uppercase and lowercase characters, so A and a are not the same variable. </li></ul><ul><li>Avoid Using Function Names for Variables </li></ul>
  13. 13. Local Variables <ul><li>Each MATLAB function has its own local variables. </li></ul><ul><li>These are separate from those of other functions, and from those of the base workspace. </li></ul>
  14. 14. Local Variables <ul><li>Variables defined in a function do not remain in memory from one function call to the next, </li></ul><ul><li>unless they are defined as global or persistent . </li></ul>
  15. 15. Local Variables <ul><li>Scripts, on the other hand, do not have a separate workspace. They store their variables in a workspace that is shared with the caller of the script. When called from the command line, they share the base workspace. When called from a function, they share that function's workspace. </li></ul>
  16. 16. Global Variables <ul><li>If several functions all declare a particular name as global , then they all share a single copy of that variable. </li></ul><ul><li>Any assignment to that variable, in any function, is available to all the other functions declaring it global . </li></ul>
  17. 17. Global Variables <ul><li>Creating Global Variables </li></ul><ul><li>Each function that uses a global variable must first declare the variable as global. </li></ul><ul><li>You would declare global variable MAXLEN as follows: </li></ul><ul><li>global MAXLEN </li></ul><ul><li>To access the variable from the MATLAB command line, you must declare it as global at the command line. </li></ul>
  18. 18. Global Variables <ul><li>Suppose, for example, you want to study the effect coefficients on a equation. Create an M-file, myfunction.m. </li></ul><ul><li>function yp = myfunction(y) </li></ul><ul><li>%The function you want to check. </li></ul><ul><li>global ALPHA </li></ul><ul><li>yp = [y-ALPHA*y]; </li></ul>
  19. 19. Global Variables Then in the command prompt enter the statements global ALPHA ALPHA = 0.01 y=myfunction(1:10); The global statement make the values assigned to ALPHA at the command prompt available inside the function defined by myfunction.m. They can be modified interactively and new solutions obtained without editing any files.
  20. 20. Persistent Variables <ul><li>Characteristics of persistent variables are: </li></ul><ul><li>You can only use them in functions. </li></ul><ul><li>Other functions are not allowed access to them. </li></ul><ul><li>MATLAB does not clear them from memory when the function exits, so their value is retained from one function call to the next. </li></ul>
  21. 21. Persistent Variables <ul><li>You must declare persistent variables as persistent before you can use them in a function. It is usually best to put persistent declarations toward the beginning of the function. You would declare persistent variable X as follows: </li></ul><ul><li>persistent X </li></ul>
  22. 22. Special Values <ul><li>ans : Most recent answer (variable). If you do not assign an output variable to an expression, MATLAB automatically stores the result in ans. </li></ul><ul><li>pi : 3.1415926535897... </li></ul>
  23. 23. Operators <ul><li>The MATLAB operators fall into three categories: </li></ul><ul><li>Arithmetic operators - perform numeric computations </li></ul><ul><li>Relational operators - compare operands quantitatively </li></ul><ul><li>Logical operators - use the logical operators AND, OR </li></ul>
  24. 24. Arithmetic Operators Unary plus + Left division . Right division ./ Multiplication .* Subtraction - Addition + Description Operator
  25. 25. Arithmetic Operators Matrix power ^ Matrix left division Matrix right division / Matrix multiplication * Complex conjugate transpose ' Transpose .' Power .^ Colon operator : Unary minus - Description Operator
  26. 26. Arithmetic Operators / Slash or matrix right division. B/A is roughly the same as B*inv(A). More precisely, B/A = (A'B')'. ./ Array right division. A./B is the matrix with elements A(i,j)/B(i,j). A and B must have the same size, unless one of them is a scalar.
  27. 27. Arithmetic Operators <ul><li> Backslash or matrix left division. </li></ul><ul><li>If A is a square matrix, AB is inv(A)*B. </li></ul><ul><li>. Array left division. </li></ul><ul><li>A.B is the matrix with elements B(i,j)/A(i,j). A and B must have the same size, unless one of them is a scalar. </li></ul>
  28. 28. Relational Operators Greater than > Less than or equal to <= Less than < Description Operator
  29. 29. Relational Operators Not equal to ~= Equal to == Greater than or equal to >= Description Operator
  30. 30. <ul><li>MATLAB offers three types of logical operator and functions. </li></ul><ul><ul><li>Element-wise - operate on corresponding elements of logical arrays. </li></ul></ul><ul><ul><li>Bit-wise - operate on corresponding bits of integer values or arrays. </li></ul></ul><ul><ul><li>Short-circuit - operate on scalar, logical expressions. </li></ul></ul>Logical Operators
  31. 31. Element-Wise Operators and Functions <ul><li>Perform element-wise logical operations on their inputs to produce a like-sized output array. </li></ul>
  32. 32. Element-Wise Operators and Functions <ul><li>A and b must have equal dimensions, with each dimension being the same size. </li></ul>
  33. 33. <ul><li>Perform AND and OR operations on logical expressions containing scalar values. </li></ul><ul><li>They are short-circuit operators in that they only evaluate their second operand when the result is not fully determined by the first operand. </li></ul>Short-Circuit Operators
  34. 34. Short-Circuit Operators Returns true (1) if either input, or both, evaluate to true, and false (0) if they do not. || Returns true (1) if both inputs evaluate to true, and false (0) if they do not. && Description Operator
  35. 35. Short-Circuit Operators Example: if ((A==10)&&(B==20)) … .. end if ((A==10)||(B==20)) … .. end
  36. 36. Flow Control <ul><li>if , else and elseif , executes a group of statements based on some logical condition. </li></ul><ul><li>switch , case and otherwise , executes different groups of statements depending on the value of some logical condition. </li></ul><ul><li>while executes a group of statements an indefinite number of times, based on some logical condition. </li></ul>
  37. 37. Flow Control <ul><li>for executes a group of statements a fixed number of times. </li></ul><ul><li>continue passes control to the next iteration of a for or while loop, skipping any remaining statements in the body of the loop. </li></ul><ul><li>break terminates execution of a for or while loop. </li></ul><ul><li>return causes execution to return to the invoking function. </li></ul><ul><li>All flow constructs use end to indicate the end of the flow control block. </li></ul>
  38. 38. Flow Control
  39. 39. Flow Control
  40. 40. Flow Control Unlike the C language switch construct, the MATLAB switch does not &quot;fall through.&quot; That is, if the first case statement is true, other case statements do not execute. Therefore, break statements are not used.
  41. 41. Flow Control switch can handle multiple conditions in a single case statement by enclosing the case expression in a cell array.
  42. 42. Flow Control <ul><li>The while loop executes a statement or group of statements repeatedly as long as the controlling expression is true (1). </li></ul><ul><li>while expression </li></ul><ul><li>statements </li></ul><ul><li>end </li></ul><ul><li>Exit a while loop at any time using the break statement. </li></ul>Infinite loop
  43. 43. Flow Control The for loop executes a statement or group of statements a predetermined number of times. for index = indexstart:increment:indexend statements end default increment is 1 .You can specify any increment, including a negative one . x=[1,2,3,8,4]; for i = 2:6 x(i) = 2*x(i-1); end You can nest multiple for loops. x=[1,2,3,8,4;4 9 7 10 15]; m=length(x(:,1)); n=length(x(1,:)); for i = 1:m for j = 1:n A(i,j) = 1/(i + j - 1); end end
  44. 44. Vectorizing Loops MATLAB is designed for vector and matrix operations. You can often speed up your M-file code by using vectorizing algorithms that take advantage of this design. Vectorization means converting for and while loops to equivalent vector or matrix operations. Compute the sine of 1001 values ranging from 0 to 10. tic i = 0; for t = 0:.001:10 i = i+1; y(i) = sin(t); end toc; t=toc A vectorized version of the same code is: tic t = 0:.001:10; y = sin(t); toc
  45. 45. File Handling <ul><li>The most commonly used, high-level, file I/O functions in MATLAB are save and load . </li></ul><ul><li>save </li></ul><ul><li>Saves workspace variables on disk. </li></ul><ul><li>As an alternative to the save function, select Save Workspace As from the File menu in the MATLAB desktop, or use the Workspace browser. </li></ul>
  46. 46. File Handling <ul><li>Syntax </li></ul><ul><li>save </li></ul><ul><li>save filename </li></ul><ul><li>save filename var1 var2 ... </li></ul><ul><li>save('filename', ...) </li></ul><ul><li>Description </li></ul><ul><li>save by itself, stores all workspace variables in a binary format in the current directory in a file named matlab.mat. Retrieve the data with load. </li></ul>
  47. 47. File Handling <ul><li>Load workspace variables from disk </li></ul><ul><li>Syntax </li></ul><ul><li>load </li></ul><ul><li>load filename </li></ul><ul><li>load filename X Y Z </li></ul>
  48. 48. File Handling <ul><li>Description </li></ul><ul><li>load - loads all the variables from the MAT-file matlab.mat , if it exists, and returns an error if it doesn't exist. </li></ul><ul><li>load filename X Y Z ... loads just the specified variables from the MAT-file. The wildcard '*' loads variables that match a pattern (MAT-file only). </li></ul>
  49. 49. File Handling <ul><li>Use the functional form of load, such as load('filename') , when the file name is stored in a string, when an output argument is requested, or if filename contains spaces. To specify a command line option with this functional form, specify the option as a string argument, including the hyphen. </li></ul><ul><li>For example, load('myfile.dat‘,’-mat’) </li></ul>
  50. 50. File Handling <ul><li>Read an ASCII delimited file into a matrix Graphical Interface </li></ul><ul><li>As an alternative to dlmread, use the Import Wizard. To activate the Import Wizard, select Import data from the File menu. </li></ul><ul><li>Syntax </li></ul><ul><li>M = dlmread(filename,delimiter) </li></ul><ul><li>M = dlmread(filename,delimiter,R,C) </li></ul><ul><li>M = dlmread(filename,delimiter,range) </li></ul>
  51. 51. File Handling <ul><li>Description </li></ul><ul><li>M = dlmread(filename,delimiter) reads numeric data from the ASCII delimited file filename, using the specified delimiter. </li></ul><ul><li>default delimiter - comma (,) </li></ul><ul><li>' ‘ - tab </li></ul><ul><li>M = dlmread(filename,delimiter,R,C) reads numeric data from the ASCII delimited file filename, using the specified delimiter. </li></ul><ul><li>The values R and C specify the row and column where the upper-left corner of the data lies in the file. R and C are zero based so that R=0, C=0 specifies the first value in the file, which is the upper left corner. </li></ul>
  52. 52. File Handling <ul><li>M = dlmread(filename,delimiter,range) reads the range specified by range = [R1 C1 R2 C2] where (R1,C1) is the upper-left corner of the data to be read and (R2,C2) is the lower-right corner. </li></ul><ul><li>Remarks </li></ul><ul><li>dlmread fills empty delimited fields with zero. Data files having lines that end with a non-space delimiter, such as a semi-colon, produce a result that has an additional last column of zeros. </li></ul>
  53. 53. File Handling <ul><li>Write a matrix to an ASCII delimited file Syntax </li></ul><ul><li>dlmwrite(filename,M,delimiter) </li></ul><ul><li>dlmwrite(filename,M,delimiter,R,C) </li></ul><ul><li>Description </li></ul><ul><li>dlmwrite(filename,M,delimiter) writes matrix M into an ASCII-format file, using delimiter to separate matrix elements. </li></ul><ul><li>default delimiter - comma (,) </li></ul><ul><li>' ' – tab delimiter </li></ul>
  54. 54. Thank You