Presentation is loading. Please wait.

Presentation is loading. Please wait.

MATLAB Fundamentals. MATLAB Matrix Laboratory Why MATLAB? Industry standard software application Wealth of built-in functions and libraries Toolboxes.

Similar presentations


Presentation on theme: "MATLAB Fundamentals. MATLAB Matrix Laboratory Why MATLAB? Industry standard software application Wealth of built-in functions and libraries Toolboxes."— Presentation transcript:

1 MATLAB Fundamentals

2 MATLAB Matrix Laboratory

3 Why MATLAB? Industry standard software application Wealth of built-in functions and libraries Toolboxes (add-on software modules) – image and signal processing, control systems design, fuzzy logic, etc. Has own structured programming language Ease of application and testing (pre- and post- processing without lots of programming and formatting) Platform independent

4 MATLAB MATLAB is a numerical analysis system Can write “programs”, but they are not formally compiled Should still use structured programming Should still use comments Comments are indicated by “ % ” at the beginning of the line

5 MATLAB Windows Command Window -- enter commands and data -- print results Graphics Window -- display plots and graphs Edit Window -- create and modify m-files

6 Matlab Windows oCommand line Interface ( Main Window) oEditor Window oPresent Directory oDirectory Contents and Workspace variables oCommand line oCommand History

7 Managing MATLAB Environment who or whos -- See the current runtime environment clear -- remove all variables from memory clc -- clear the command window clf -- clear the graphics window save -- save the workspace environment load -- restore workspace from a disk file abort -- CTRL-C help -- help “command” Really good “ help ” command

8 MATLAB Syntax No complicated rules Perhaps the most important thing to remember is semicolons (;) at the end of a line to suppress output

9 MATLAB MATLAB’s basic component is a Vector or Matrix Even single value variables (Scalars) All operations are optimized for vector use Loops run slower in MATLAB than in Fortran (not a vector operation) “ size ” command gives size of the matrix

10 Scalars, Vectors, Matrices MATLAB treat variables as “matrices” Matrix (m  n) - a set of numbers arranged in rows (m) and columns (n) Scalar: 1  1 matrix Row Vector: 1  n matrix Column Vector: m  1 matrix

11 >> pi ans = 3.1416 >> size(pi) ans =1 1 >> a=[1 2 3; 4 5 6] a = 1 2 3 4 5 6 >> size(a) ans = 2 3 a=

12 Complex variables MATLAB handles complex arithmetic automatically No need to compute real and imaginary parts separately The unit imaginary number i = is preassigned » x=5+2*i x = 5.0000 + 2.0000i » y=5*x+3 y = 28.0000 +10.0000i

13 » x=3+5-0.2 x = 7.8000 » y=3*x^2+5 y = 187.5200 » z=x*sqrt(y) z = 106.8116 » A=[1 2 3; 4 5 6] A = 1 2 3 4 5 6 » b=[3;2;5] b = 3 2 5 » C=A*b C = 22 52 » who Your variables are: A b y C x z » whos Name Size Bytes Class A 2x3 48 double array C 2x1 16 double array b 3x1 24 double array x 1x1 8 double array y 1x1 8 double array z 1x1 8 double array MATLAB Example

14 Data types All numbers are double precision Text is stored as arrays of characters You don’t have to declare the type of data (defined when running) MATLAB is case-sensitive!!! MATLAB is case-sensitive!!!

15 Variable Names Usually, the name is identified with the problem Variable names may consist of up to 31 characters Variable names may be alphabetic, digits, and the underscore character ( _ ) Variable names must start with a letter ABC, A1, C56, CVEN_302 day, year, iteration, max time, velocity, distance, area, density, pressure (case sensitive!!) Time, TIME, time (case sensitive!!)

16 Initializing Variables Explicitly list the values reads from a data file uses the colon (:) operator reads from the keyboard A = [1; 3; 5; 10]; B = [1 3 5; -6 4 -1] C = [2 3 5 1; 0 1 … (continuation) 1 -2; 3 5 1 -3] E = [A; 1; A]; F = [C(2,3); A]

17 Matrix Concatenation

18 Colon Operator Creating new matrices from an existing matrix C = [1,2,5; -1,0,1; 3,2,-1; 0,1,4] F = C(:, 2:3) = [2,5; 0,1; 2,-1; 1,4]

19 Colon Operator Creating new matrices from an existing matrix C = [1,2,5; -1,0,1; 3,2,-1; 0,1,4] E = C(2:3,:) = [-1 0 1; 3 2 -1]

20 Colon Operator Creating new matrices from an existing matrix C = [1,2,5; -1,0,1; 3,2,-1; 0,1,4] G = C(3:4,1:2) = [3,2; 0,1]

21 Colon Operator Variable_name = a:step:b time = 0.0:0.5:2.5 time = [0.0, 0.5, 1.0, 1.5, 2.0, 2.5] Negative increment values = 10:-1:2 values = [10, 9, 8, 7, 6, 5, 4, 3, 2]

22 linspace Function linspace(x1, x2) gives 100 evenly spaced values between x1 and x2 x = linspace(x1,x2) linspace(a,b,n) generate n equally spaced points between a and b x = linspace(a,b,n) » linspace(0,2,11) ans = Columns 1 through 7 0 0.2000 0.4000 0.6000 0.8000 1.0000 1.2000 Columns 8 through 11 1.4000 1.6000 1.8000 2.0000

23 logspace Function logspace(a,b,n) generates a logarithmically equally spaced row vector x = logspace(a,b,n) logspace(a,b) generates 50 logarithmically equally spaced points x = logspace(a,b) » logspace(-4,2,7) ans = 0.0001 0.0010 0.0100 0.1000 1.0000 10.0000 100.0000

24 Special Matrices

25 Scalar Arithmetic Operations Example: x = (a + b*c)/d^2 count = count + 1 (Matrix inverse)  In order of priority

26 Order of Precedence of Arithmetic Operations 1.Parentheses, starting with the innermost pair 2.Exponentiation, from left to right 3.Multiplication and division with equal precedence, from left to right 4.Addition and subtraction with equal precedence, from left to right Examples: factor = 1 + b/v + c/v^2 slope = (y2 - y1)/(x2 - x1) loss = f * length/dia * (1/2 * rho * v^2) func = 1 + 0.5*(3*x^4 + (x + 2/x)^2)

27 Order of Precedence of Arithmetic Operations  The priority order can be overridden with parentheses » y = -7.3^2 y = -53.2900 » y=(-7.3)^2 y = 53.2900 » a=3; b=5; c=2; » s1 = a-b*c s1 = -7 » s2=(a-b)*c s2 = -4 Exponentiation has higher priority than negation Multiplication has higher priority than subtraction

28 Array Operations An array operation is performed element-by-element MATLAB: C = A.*B;

29 Element-by-Element Operations

30 But a*b gives an error (undefined) because dimensions are incorrect. Need to use.* Vector and Matrix operations

31 Vectorized Matrix Operations

32 Array Operations for m  n Matrices

33 Matrix Transpose

34 Built-in Functions All the standard operators +, , *, /, ^ Sqrt( ), abs( ), sin( ), cos( ), exp( ), tanh( ), acos( ), log( ), log10( ), etc. These operators are vectorized

35 Built-in Functions Certain functions, such as exponential and square root, have matrix definition also Use “help expm” and “help sqrtm” for details >> A = [1 3 5; 2 4 6; -3 2 -1] A = 1 3 5 2 4 6 -3 2 -1 >> B = sqrt(A) B = 1.0000 1.7321 2.2361 1.4142 2.0000 2.4495 0 + 1.7321i 1.4142 0 + 1.0000i >> C = sqrtm(A) C = 2.1045 + 0.0000i 0.1536 - 0.0000i 1.8023 + 0.0000i 1.7141 - 0.0000i 1.1473 + 0.0000i 1.7446 + 0.0000i -2.0484 + 0.0000i 1.3874 + 0.0000i 0.5210 - 0.0000i (element by element) (C*C = A)

36 MATLAB Graphics One of the best things about MATLAB is interactive graphics “ plot ” is the one you will be using most often Many other 3D plotting functions -- plot3, mesh, surfc, etc. Use “ help plot ” for plotting options To get a new figure, use “ figure ” logarithmic plots available using semilogx, semilogy and loglog

37 plot(x,y) defaults to a blue line plot(x,y,’ro’) uses red circles plot(x,y,’m*’) uses magenta asterisks If you want to put two plots on the same graph, use “ hold on ” plot(a,b,’r:’) (red dotted line) hold on plot(a,c,’ko’) (black circles) Plotting Commands

38 Color, Symbols, and Line Types Use “help plot” to find available Specifiers b blue. point - solid g green o circle : dotted r red x x-mark -. dashdot c cyan + plus -- dashed m magenta * star y yellow s square k black d diamond v triangle (down) ^ triangle (up) < triangle (left) > triangle (right) p pentagram h hexagram Colors Symbols Line Types

39 » x=0:0.1:5; » y=2*x.^3-12*x.^2+8*x-6; » H=plot(x,y,'b',x,y,'r*'); » set(H,'LineWidth',3,'MarkerSize',12) » xlabel('x'); ylabel('y'); » title('f(x)=2x^3-12x^2+8x-6'); element-by-element operations x.^n Adjust line thickness, font size, marker size, etc.

40 » x=0:0.1:10; » y=sin(2.*pi*x)+cos(pi*x); » H1=plot(x,y,'m'); set(H1,'LineWidth',3); hold on; » H2=plot(x,y,'bO'); set(H2,'LineWidth',3,'MarkerSize',10); hold off; » xlabel('x'); ylabel('y'); » title('y = sin(2\pix)+cos(\pix)');

41 » x=0:0.1:3; y1=exp(-x); y2=sqrt(x); » H=plot(x,y1,'b-',x,y2,'r--'); » set(H,'LineWidth',3) » xlabel('x'); ylabel('y'); title('MATLAB Plots'); » H1=text(1.8,0.2,'exp(-x)'); set(H1,'FontSize',18); » H2=text(1.8,1.3,'sqrt(x)'); set(H2,'FontSize',18);

42 plot (x, y)plot(x1, y1, x2, y2) plot (x, y, ‘color symbol line style’) » x = linspace(0, 2*pi); » y = sin (2.*x); » z = cos (0.5*x); » plot (x, y) » plot (x, y, x, z) » figure (2) » plot (x, y, 'r o -'); grid on » hold on » plot (x, z, 'b * :') (red, circle, solid line) (blue, star, dotted line) figure or figure (#) : open a figure Plotting Commands

43 » xlabel (Time) » ylabel (Temperature) » title (Temperature Record : 1900 - 2000) » text (17, 120, Record High ) » text (85, -40, Record Low ) » axis ([0 100 -50 140]) » hold off xlabel ( label )ylabel ( label ) title ( title of the plot ) text ( x_location, y_location, text ) axis ( [ x_min x_max y_min y_max ] ) - text string Graphics Commands Axis, Labels, and Title

44 Flow Control Simple if statement: if logical expression commands end Example: (Nested) if d <50 count = count + 1; disp(d); if b>d b=0; end Example: (else and elseif clauses) if temperature > 100 disp (‘Too hot – equipment malfunctioning.’) elseif temperature > 90 disp (‘Normal operating range.’); elseif (‘Below desired operating range.’) else disp (‘Too cold – turn off equipment.’) end

45 Flow Control (con’t…) The switch statement: switch expression case test expression 1 commands case test expression 2 commands otherwise commands end Example: switch interval < 1 case 1 xinc = interval /10; case 0 xinc = 0.1; end

46 Loops for loop for variable = expression commands end while loop while expression commands end Example (for loop): for t = 1:5000 y(t) = sin (2*pi*t/10); end Example (while loop): EPS = 1; while ( 1+EPS) >1 EPS = EPS/2; end EPS = 2*EPS the break statement break – is used to terminate the execution of the loop.

47 Introduction to M-Files – The Edit Window – MATLAB Script Files – Input / Output Messaging – Anonymous Functions – Function Files – Basics of Programming

48 Programming in MATLAB – why bother? It may be very cumbersome or impossible to solve a problem by executing commands at the command prompt. Programming… – expands the scope and types of problems that you can solve. – provides a way to make complex decisions. – automates repetitive calculations.

49 Starting the Edit Window Another way to start the Edit Window is to type at the command prompt: >> edit Use the new M-File button Blank M-File creates a blank script file. Function M-File creates a file with the definition line

50 The Edit Window Blank M-File Function M-File with the definition line

51 Navigating the Edit Window New File, Open File, Save File Cut, Copy, Past, Undo, Redo, Print Save and Run your file Function Finder Debugging Tools Find within a file

52 Basic MATLAB Programs MATLAB has two basic program types: – Script file (sometimes called an “M” file) – Function file Key differences between the two file types: Function File – In addition to commands & comments, must have a function definition line (1 st line in file). – Accepts data through input variables and passes out data through output variables. – Variables are local only to the function, and are not placed in the workspace. Script File –Contains just commands and comments. –Can use variables that are already defined in the workspace. –Leaves variables in the workspace all used in the file.

53 Using History to Create an M-File You can also “jump-start” your programming by creating an M-file from commands you have already typed into the command window 1.Select the commands you want to be transferred to a new M- file 2.Right-click on one of the commands. 3.Select Create M-File from the menu.

54 Script Programming Script files are an easy to way to capture and automate a set of commands. Scripts differ from diary files in that you can “execute” a Script file. – To execute a Script file, it must be either: saved to your current directory (set at top of window) saved to a folder on your current directory path – To execute the script, type its name at the command prompt or press the button on the Edit Window toolbar.

55 Script Programming Programming a Script is just like executing commands at the command prompt. – MATLAB will execute each line in your file from top to bottom. – MATLAB will use the variables in the workspace. – Any variables you create (or modify) while the program runs will be stored in the workspace. Existing variables of the same name will be overwritten (or modified)!

56 Script Programming – Special Commands

57 Perform the following: 1.Start the Edit Window and type the following commands: 2.Save the file as simplesmooth.m and run either from the command prompt (>> simplesmooth) or from the run button. Script Programming – Try It!

58 Comment block describing what the file does Create a plot using previously defined variables xsine and ysine Smooth the data using a 5 point moving average. Create two new variables: kernel and ysmooth Add the smoothed data to the plot along with a legend Because Script files don’t remove variables created during execution, large and complicated files can quickly fill-up your workspace with lots of variables you don’t need or want.

59 Input Functions Examples: Get a number from the user Get a string from the user It is sometimes useful to get information from the user while the program is executing. One technique is through the input command. ‘s’ tells MATLAB to treat the input as a string, even if a number is entered The user input value is now stored in the variable avg_size

60 Input Functions Example: The menu command is a graphical method for getting user input. The user section (1, 2 or 3 in this example, corresponding to Red, Blue or Green) is now stored in the variable selection

61 Output Functions Examples: Display a string Display a number Display a string and variable Likewise, it is sometimes useful to write information to the Command Window. This is accomplished through the disp command. The fprintf & scanf commands provide additional control. See help for more Information. The num2str command converts a number to a string

62 Modify your program as follows: Save the file & run it. Try different points in the average. Script Programming – Try It! To write robust programs, you’ll need to start thinking about all the ways a program can fail – then guard against them. -Inputting a negative # -A string instead of a #...

63 Creating a Shortcut A shortcut is an easy way to run a group of MATLAB statements. A shortcut is more convenient than an M-file because it does not have to be in the current directory or on the MATLAB search path when you run it. To create and run a shortcut: –Select a statement or group of statements from the Command History window, the Command Window, or an M-file. –Drag the selection to the desktop Shortcuts toolbar. –Name the shortcut in the dialog that appears From the MATLAB Help System Shortcuts can be useful for repetitive tasks like giving plots a consistent formatting, or clearing your workspace. If you copy the statements from the Command Window, prompts (>>) appear in the shortcut, but MATLAB removes the prompts when you save the shortcut.

64 Perform the following: 1.Select all the lines from your simplesmooth.m file, and 2.Drag these lines to the Shortcut bar 3.Assign the shortcut the name Smooth Sine in the Shortcut Editor dialog. 4.Run the shortcut by clicking it. Creating a Shortcut – Try It! 1 2

65 Anonymous Functions Anonymous functions give you a quick means of creating simple functions without having to create M-files each time. You construct an anonymous function at the MATLAB command prompt. >> function_name = @(argument list) expression The equation you want to name Comma-separated list of input variables Tells MATLAB to create an anonymous function The name for your anonymous function You can create a function handle to any MATLAB function. The constructor uses a different syntax: fhandle = @functionname (e.g., ln = @log).

66 Anonymous Functions – Try It! Define an anonymous function ln. Create an anonymous function that squares a number. Because sqr is a function handle, you can pass it in an argument list to other functions. Example of an anonymous function with a two input variables. Perform the following: >> ln = @log >> ln(1) >> log(1) >> sqr = @(x) x.^2 >> sqr(5) >> quad(sqr,0,1) >> sumxy = @(x, y) (5*x +2*y); >> sumAxBy(5, 7) Anonymous functions remain active until you clear them from your workspace or restart MATLAB. Create a Shortcut of any anonymous function you create regularly.

67 Creating a Function File

68 Function File Format A Function M-File contains: 1.a function definition line 2.a comment block and 3.blank space for your code 4.an end statement 1 2 3 4

69 Function File Format Function M-Files must have a function definition line and a corresponding end command!

70 Function File Format Comma separated list of the variables the function passes out. Omit this and the “=“if the function passes nothing out. This is where you name your function. This name should match the name you save the file with. Comma separated list of the variables passed into the function.

71 Function File Format Summary block. This is where you type in your description of the function. Use additional “%” to create extra lines. This information gets displayed to the user when they type help on the function.

72 Function File Format Place your lines of code between the bottom of the comment block and the closing end statement.

73 Perform the following: 1.Open your simplesmooth.m file. 2.Create a new function M-file from the menu. 3.Copy your simplesmooth.m commands into the new file. 4.Close simplesmooth.m 5.Modify the new function as follows on the next slide. Function Programming – Try It!

74 Enter in your own comments Modify the function line Save your file with the name smoothfcn.m Get rid of the input command that was here.

75 Perform the following: 1.Clear all variables from your workspace except xsine and ysine. 2.At the command prompt, type: >> [ysmoothed] = smoothfcn(xsine,ysine,8); Notice that a new variable has been created in your workspace named ysmoothed. Also note that avg_size, kernel and ysmooth were not created in your Workspace. They were created within the Function and were eliminated when the function completed execution. 3.At the command prompt, type: >> [ysmoothed] = smoothfcn(ysine,xsine,8); What’s going on? Function Programming – Try It!

76 Function Programming >> [ysmoothed] = smoothfcn(ysine,xsine,8); The order you pass variables into the function matters! This function always uses the first variable passed in for x, and the second for y.

77 One Last Comment on M-Files Consider this scenario: – You are working on building a file. The file is open in the Edit Window. – You make changes in your file, and rerun the file from the Command Prompt ( >> ), but your results don’t change. – What’s going on? Make sure that… – the file you are editing is the same one that is running – if you have two copies, it may be executing the other. – you save the file before running. If it still isn’t working, type >> clear functions at the Command Prompt. This will force MATLAB to recompile all M-Files before running them.

78 Basic “Good Coding Practices” Create descriptive variable names and function names. Keep them reasonable in length. When possible, define the key variables you are going to use in a comment block at the top of the program. Unless self-explanatory, all lines and/or blocks of code must always be commented. When writing a function, an overall description of the function, preferably with its syntax, must always appear directly below the function statement. Indent and space blocks of code to improve organization and readability of the code. This facilitates code modification & debugging activities. Break up larger programs into a main program with calls to smaller, specialized programs. Use flowcharting and pseudocode when starting a project to help organize what you need to do.

79 Using Pseudo Code Pseudocode is like a recipe – tells you what to do, but doesn’t give you the specifics on how to do it. Constructing pseudocode –Outline a set of statements describing the steps you will take to solve a problem –Convert these steps into comments in an M-file –Insert the appropriate MATLAB code into the file between the comment lines. Write a program to convert mph to km/hr Get mph from user Apply conversion to km/hr Return value to user % Input mph % Convert % Tell user % Input mph mph = input(‘Enter the mph: ‘); % Convert kph = mph*1.609; % Tell user s = [‘num2str(mph)’ mph = ‘,num2str(kph),’ km/hr’]; disp(s);


Download ppt "MATLAB Fundamentals. MATLAB Matrix Laboratory Why MATLAB? Industry standard software application Wealth of built-in functions and libraries Toolboxes."

Similar presentations


Ads by Google