Presentation is loading. Please wait.

Presentation is loading. Please wait.

Matlab. Textbooks Required:, by Palm (3 rd edition) Required: Introduction to MATLAB for Engineers, by Palm (3 rd edition)

Similar presentations


Presentation on theme: "Matlab. Textbooks Required:, by Palm (3 rd edition) Required: Introduction to MATLAB for Engineers, by Palm (3 rd edition)"— Presentation transcript:

1 Matlab

2 Textbooks Required:, by Palm (3 rd edition) Required: Introduction to MATLAB for Engineers, by Palm (3 rd edition)

3 Purchasing MATLAB Software Mathworks web site: (http://www.mathworks.com). Mathworks web site: (http://www.mathworks.com). UH Bookstore—be sure to get version 7 UH Bookstore—be sure to get version 7 UH-IT Department UH-IT Department

4 About MATLAB a computer programming language a computer programming language a software environment for using the language effectively a software environment for using the language effectively MATLAB is…

5 Two modes of operation Interactive calculator mode Interactive calculator mode Script mode: execution of complete programs  script files Script mode: execution of complete programs  script files About MATLAB

6 Running MATLAB creates one or more windows Running MATLAB creates one or more windows One is called the MATLAB Desktop: Primary graphical user interface for MATLAB One is called the MATLAB Desktop: Primary graphical user interface for MATLAB Contains and manages all other windows that are part of MATLAB Contains and manages all other windows that are part of MATLAB According to the configuration some windows may be visible and some may not. You can see this information in the View Menu According to the configuration some windows may be visible and some may not. You can see this information in the View Menu About MATLAB

7 About MATLAB Desktop

8 MATLAB Desktop Windows: MATLAB Desktop Windows: – Command Window: Primary place to interact with MATLAB. Place where the user issues the commands. The MATLAB command prompt is the symbol >> – Command History: Running history of prior commands issued in the Command Window. About MATLAB Desktop

9 MATLAB Desktop Windows: MATLAB Desktop Windows: – Workspace: GUI for viewing, loading, and saving MATLAB variables. – Launch Pad: Tree layout for access to tools, demos and documentation – Current Directory: GUI for directory and file manipulation in MATLAB. About MATLAB Desktop

10 MATLAB Desktop Windows: MATLAB Desktop Windows: – Help: GUI for finding and viewing on-line documentation. – Array Editor: GUI for modifying the content of MATLAB variables – Editor/Debugger: Text editor and debugger for MATLAB text files. About MATLAB Desktop

11 What does Matlab understand? Real numbers: 1 -14 7.65432 2e3 Real numbers: 1 -14 7.65432 2e3 Complex numbers: 2+3i 4-6j 2i Complex numbers: 2+3i 4-6j 2i Arrays of numbers: [1,2,3] [1,2;3,4] Arrays of numbers: [1,2,3] [1,2;3,4] Strings: ‘I wish I knew that!’ Strings: ‘I wish I knew that!’

12 Basics: Basic Operations SymbolOperationMATLAB ^ exponentiation: a b a^b * multiplication: ab a*b / right division: a/b = a/b \ left division: a\b = a\b + addition: a + b a+b - subtraction: a-b a-b

13 PrecedenceOperation First Parentheses, evaluated starting with the innermost pair. Second Exponentiation, evaluated from left to right. Third Multiplication and division with equal precedence, evaluated from left to right. Fourth Addition and subtraction with equal precedence, evaluated from left to right. Basics: Rules of Precedence

14 precedence examples precedence examples »8 + 3 * 5 (8 + (3 * 5)) = 23 (8 + (3 * 5)) = 23 »4 ^ 2 – 12 – 8 / 4 * 2 ((4 ^ 2) – 12 – ((8 / 4) * 2))) = 0 ((4 ^ 2) – 12 – ((8 / 4) * 2))) = 0 »3 * 4 ^ 2 + 5 ((3 * (4 ^ 2)) + 5) = 53 ((3 * (4 ^ 2)) + 5) = 53 »27 ^ 1 / 3 + 32 ^ 0.2 (((27 ^ 1) / 3 )+ (32 ^ 0.2))=11 (((27 ^ 1) / 3 )+ (32 ^ 0.2))=11 Basics: Rules of Precedence

15 Basics: Variables Variable is a symbol used to contain a value Variable is a symbol used to contain a value MATLAB has some rules to name variables MATLAB has some rules to name variables –Variables names are case sensitive »BOB, Bob, bob, BoB  all different! –Variables names can contain up to 31 characters. Any additional characters are ignored –Variable names must start with a letter, followed by any number of letters, digits or underscores. Punctuation characters are not allowed, because most of them have a special meaning in MATLAB

16 Some names cannot be used for variables: for, end, if, while, function, return, elseif, case, otherwise, switch, continue, else, try, catch, global, persistent, break Some names cannot be used for variables: for, end, if, while, function, return, elseif, case, otherwise, switch, continue, else, try, catch, global, persistent, break If you try to use any of these reserved words as a variable, MATLAB will report an error If you try to use any of these reserved words as a variable, MATLAB will report an error Of course, you can use words similar by capitalizing one or more letters Of course, you can use words similar by capitalizing one or more letters Also, MATLAB has a number of special variables and constants Also, MATLAB has a number of special variables and constants Basics: Variables

17 Basics: Special Variables and Constants NameDescription ans Default variable name used for results eps specifies accuracy of f.p. precision i,j imaginary unit, sqrt(-1) Infinfinity NaN undefined numerical result pi realmax largest real f.p. # on THIS computer realmin smallest real f.p. # on THIS computer

18 Basics Assignment or replacement operator: = Assignment or replacement operator: = It works different than the equal sign: the variable on the left-hand side is replaced by the value generated by the right-hand side. Therefore, only one variable name must be in the left-hand side It works different than the equal sign: the variable on the left-hand side is replaced by the value generated by the right-hand side. Therefore, only one variable name must be in the left-hand side –x = x – 2 –6 = x  NOT VALID!!! The right-hand side must have a computable value The right-hand side must have a computable value –x = 5 + y; Is y defined?

19 Basics Example: Volume of a circular cylinder Example: Volume of a circular cylinder Given a circular cylinder with height 15m and radius 8 m, find the radius of a cylinder of the same height but with a volume that is 20% larger.

20 Solution Algorithm Calculate current volume Calculate current volume Calculate desired volume Calculate desired volume Determine new radius by rewriting volume equation in terms of radius: Determine new radius by rewriting volume equation in terms of radius:

21 Basics The formula for volume is V=  r 2 h The formula for volume is V=  r 2 h The radius is given by: The radius is given by: >> r = 8; >> h = 15; >> V = pi*r^2*h >> newV = 1.2*V >> newr = sqrt(newV/(pi*h)) ans = 8.7636

22 Basics: Commands CommandDescription clcclears Command window clearremoves all variables clear var1 var2removes listed variables exist (‘name’)determines if name (file or var) exists quitStops MATLAB wholists current variables whoslists current variables with sizes :generates array,separates elements of array ;suppresses screen printing, also new line in array …continues a line

23 Basics: Complex Numbers complex number ex: complex number ex: complex number complex number »s = 3 + 7i »w = 5 – 9i MATLAB Ex. MATLAB Ex. –Given x = -5 + 9i and y = 6 – 2i –find x + y=x + y=1+7i x*y =x*y = -12 + 64i -12 + 64i x/y =x/y = -1.2 + 1.1i

24 Some Simple Functions sin(x) sin(x) sqrt(x) sqrt(x) acos(x) acos(x) exp(x) exp(x) log(x) log(x)

25 Interpretation sin(180) ????? sin(180) ????? acos(.5) ????? acos(.5) ????? exp(1) ????? exp(1) ????? log(10) ????? log(10) ?????

26 Polynomials in Matlab A polynomial is represented by its array of coefficients, beginning with the “leading” coefficient (coefficient of highest power): A polynomial is represented by its array of coefficients, beginning with the “leading” coefficient (coefficient of highest power):

27 Special Polynomial Functions polyval(a,x): evaluates polynomial whose coefficients are in array a at the point x polyval(a,x): evaluates polynomial whose coefficients are in array a at the point x roots(a): returns a vector containing all of the roots of the polynomial whose coefficients are in the array a roots(a): returns a vector containing all of the roots of the polynomial whose coefficients are in the array a poly(v): returns the coefficient vector of a polynomial whose roots are stored in the vector v poly(v): returns the coefficient vector of a polynomial whose roots are stored in the vector v

28 Polynomial Examples >> a=[2,4,-1,5]; >> polyval(a,0) ans = 5 >> poly([1, 2, 3]) ans = 1 -6 11 -6 1 -6 11 -6 >> v=roots(a) v = -2.5722 0.2861 + 0.9434i 0.2861 - 0.9434i

29 Plotting in Matlab The basic command to plot a set of points in the plane is plot(x,y) The basic command to plot a set of points in the plane is plot(x,y) x is a vector containing the horizontal coordinates x is a vector containing the horizontal coordinates y is a vector containing the vertical coordinates y is a vector containing the vertical coordinates x & y must be the same size—either both row vectors or both column vectors x & y must be the same size—either both row vectors or both column vectors The plot actually appears in a separate window, called a “figure” window. The plot actually appears in a separate window, called a “figure” window.

30 Plotting Example >> x=[0:.01:10]; %generate x values >> y=sin(x); %generate y values --sin function %applied to array of x’s %applied to array of x’s >> figure(1) %give number to figure >> plot(x,y),title('My first Plot'),xlabel('x axis'),... ylabel('y axis')

31

32 CommandDescription plot(x,y) Generates plot. title(‘text’) Puts title on plot. xlabel(‘text’) Adds label to horizontal axis. ylabel(‘text’) Adds label to vertical axis. legend Places a legend figure n Opens a new figure window numbered n hold on Holds on the current graph Plotting in MATLAB

33 Some Plot Options Some Plot Options COLORSSYMBOLS LINE TYPES y yellow. point - solid m magenta o circle : dotted c cyan x x-mark -. dash dot r red + plus -- dashed g green * star b blue s square w white d diamond k black v,^, triangles

34 Matlab Files Script & function files—plain ASCII, extension.m Script & function files—plain ASCII, extension.m MAT files—binary file, used to “save” workspace variables, extension.mat MAT files—binary file, used to “save” workspace variables, extension.mat

35

36 >> pi ans = 3.1416 >> format long >> pi ans = 3.14159265358979 >> format rat >> pi ans = 355/113

37 Controlling Input and Output The disp Function: Useful to control the output The disp Function: Useful to control the output disp: Display array. disp(X) displays the array, without printing the array name. It's the same as leaving the semicolon off an expression except that empty arrays don't display. If X is a string, the text is displayed. EXAMPLES: EXAMPLES: >> disp(X) displays the value of variable X, but not its name >> disp(‘The value of X is:’) displays the string The value of X is: but no number

38 Controlling Input and Output The num2str Function: Useful to make the output look better The num2str Function: Useful to make the output look better num2str: Convert number to string. T=num2str(X) converts the array X into a string representation T with about 4 digits and an exponent if required. Allows display of label on same line as value. T=num2str(X) converts the array X into a string representation T with about 4 digits and an exponent if required. Allows display of label on same line as value. >> x=3.24567; >> disp(['The value of x is ',num2str(x),'ft']) The value of x is 3.2457ft

39 Controlling Input and Output The input Function: Used to get interactive input. The input Function: Used to get interactive input. input: Prompt for user input. input: Prompt for user input. R = input('How many apples') gives the user the prompt in the text string and waits for input from the keyboard. The input can be any MATLAB expression, which is evaluated, using the variables in the current workspace, and the result returned in R. If the user presses the return key without entering anything, INPUT returns an empty matrix. R = input('How many apples') gives the user the prompt in the text string and waits for input from the keyboard. The input can be any MATLAB expression, which is evaluated, using the variables in the current workspace, and the result returned in R. If the user presses the return key without entering anything, INPUT returns an empty matrix. R = input('What is your name','s') gives the prompt in the text string and waits for character string input. The typed input is not evaluated; the characters are simply returned as a MATLAB string. R = input('What is your name','s') gives the prompt in the text string and waits for character string input. The typed input is not evaluated; the characters are simply returned as a MATLAB string.

40 Controlling Input and Output The Menu Function: Used to get interactive input by selection of an alternative from a menu. The Menu Function: Used to get interactive input by selection of an alternative from a menu. k = menu(‘title’,’option1’,’option2’,…) k = menu(‘title’,’option1’,’option2’,…) choices=['B','D','F'];k=menu('Whodoyouwant?',choices(1),choices(2),choices(3)); disp(['You picked ',choices(k)])

41 Input from File load– as a command or as a function, requires each line in file has same number of values, loads entire contents of file into an array >>load data.txt; % name of array will be data >>load(‘new.txt’); % name of array will be new >>mydata = load(‘proj3.txt’); %name of array will be mydata


Download ppt "Matlab. Textbooks Required:, by Palm (3 rd edition) Required: Introduction to MATLAB for Engineers, by Palm (3 rd edition)"

Similar presentations


Ads by Google