Introduction to Interactive Calculations Matlab is interactive, no need to declare variables >> 2+3*4/2 >> V = 50 >> V + 2 >> V Ans = 52 >> a=5e-3; b=1; a+b Most elementary functions and constants are already defined >> cos(pi) >> abs(1+i) >> sin(pi) Variable and Memory Management The Help System Matlab uses double precision (approx. 16 significant digits) >> format long >> format compact All variables are shown with >> who >> whos Variables can be stored on file >> save filename >> clear >> load filename Search for appropriate function >> lookfor keyword Rapid help with syntax and function definition >> help function An advanced hyperlinked help system is launched by >> helpdesk Complete manuals as PDF files Vectors and Matrices Vectors (arrays) are defined as >> v = [1, 2, 4, 5] >> w = [1; 2; 4; 5] eye - Identity matrix Matrices Generation ones - Matrix with all elements = 1 Matrices (2D arrays) defined similarly >> A = [1,2,3; 4,-5,6; 5,-6,7] rand Random matrix zeros - Matrix with all elements = 0 1
Matrix Index Matrices Operations Always starts with 1 (not 0) Given: Given A and B: Addition Subtraction Product Transpose The use of. Element Operation MATLAB Math & Assignment Operators Given A: Power ^ or.^ a^b or a.^b Multiplication * or.* a*b or a.*b Division / or./ a/b or a./b or \ or.\ b\a or b.\a NOTE: 56/8 = 8\56 Divide each element of A by 2 Multiply each element of A by 3 Square each element of A - (unary) + (unary) Addition + a + b Subtraction - a - b Assignment = a = b (assign b to a) Other MATLAB symbols Matlab Desktop >> prompt... continue statement on next line, separate statements and data % start comment which s at of line ; (1) suppress output (2) used as a row separator in a matrix : specify range Launch Pad History >> radius = 50 >> radius + 10 Ans = 60 Command Window 2
The Matlab Environment Matlab is an interpreted language Commands (Statements) are typed into the COMMAND Window and executed immediately Variables are allocated in memory as soon as they are first used in an expression Commands must be re-entered to be re-executed MATLAB statements can also be put together to construct a Script which can be repeated executed as a MATLAB Program. All variables created in the Command Window are in what is called the Base Workspace Variables can be reassigned new values as needed Variables can be selectively cleared from the workspace The Workspace can be saved to a data file File extension is.mat (ex: mydata.mat) File is in binary and essentially unreadable by humans.mat files can be reloaded back into the Matlab Workspace Workspace Current DIrectory Matlab Desktop cont d Command Window Matlab Programs Programs in Matlab are: Scripts, or Functions Scripts: Matlab statements that are fed from a file into the Command Window and executed immediately Functions: Program modules that are passed data (arguments) and return a result (i.e., sin(x)) These can be created in any text editor (but Matlab supplies a nice built-in editor) New, Load, Save, etc. Comments Matlab Editor Access to commands Color keyed text with auto indents tabbed sheets for other files being edited Reserved Words Matlab has some special (reserved) words that you may not use for switch continue if else while try function catch return global elsif persistent case break otherwise Special Variable ans beep pi eps inf NaN i (or) j realmin, realmax bitmax nargin, nargout varargin varaout Description default variable name for results make sound mathematical constant smallest number that can be subtracted from 0 to make a negative infinity not a number imaginary number smallest & largest positive real numbers largest positive integer number of function in (or) out variables variable number of function in arg s variable number of function out arg s 3
Matlab Help Scripts (and Functions) Matlab s Command prompt is where you can enter commands to be executed immediately Just like a calculator You can see what you ve done but it must be re-entered at the command prompt to be recalculated Only the results (variables) are retained in the Matlab workspace (diary on will log commands and results to a diary file; diary off disables this) >> length=5.5; >> radius=2.25; >> volume=pi.*radius^2.*length volume = 87.4737 What if you want to enter different values for radius or length? Matlab Scripts Matlab scripts are the solution to this problem! You can create a script that can be repeatedly executed This is the basic Matlab program Scripts are simply text files containing Matlab statements You can use any text editor but the built-in editor indents and uses color to highlight the language syntax Script files always have the.m extension, e.g., m-files When a script (m-file) is executed, it is simply read sequentially and each line is presented to the Matlab command prompt just like it was typed by hand Speed and repeatability are key features Matlab control & loop statements (e.g., if, for, while ) can be executed in this way Script in an m-file Use File/New/M-file to start Matlab editor Save file with.m extension in directory in Matlab s path m file myscript is called by name Type m-file name at prompt to execute Enter the length of a cylinder: 8 Now enter the radius: 2.4 Volume of cylinder is: 144.76 Enter the length of a cylinder: 10 Now enter the radius: 1 Volume of cylinder is: 31.416 >> Script Workspace When commands are executed, the results are left in the Matlab BASE workspace. whos will list all the current variables in the workspace Scripts can make use of variables already defined in the Base workspace Enter the length of a cylinder: 10 Now enter the radius: 1 Volume of cylinder is: 31.416 >> whos Name Size Bytes Class length 1x1 8 double array radius 1x1 8 double array volume 1x1 8 double array Grand total is 3 elements using 24 bytes >> >> density=100; Enter the length of a cylinder: 10 Now enter the radius: 1 Weight of cylinder is: 3141.6 >> PLOT Linear plot. plot(x,y) plots vector Y versus vector X plot(y) plots the columns of Y versus their index plot(x,y,s) with plot symbols and colors See also semilogx, semilogy, title, xlabel, ylabel, axis, axes, hold, leg, subplot... x = [-3-2 -1 0 1 2 3]; y1 = (x.^2) -1; plot(x, y1,'bo-.'); 4
XLABEL X-axis label. xlabel('text') adds text beside the X-axis on the current axis. YLABEL Y-axis label. ylabel('text') adds text beside the Y-axis on the current axis.... xlabel('x values'); ylabel('y values'); HOLD Hold current graph. hold on holds the current plot and all axis properties so that subsequent graphing commands add to the existing graph. hold off returns to the default mode hold, by itself, toggles the hold state.... hold on; y2 = x + 2; plot(x, y2, 'g+:'); SUBPLOT Create axes in tiled positions. subplot(m,n,p), or subplot(mnp), breaks the Figure window into an m-by-n matrix of small axes x = [-3-2 -1 0 1 2 3]; y1 = (x.^2) -1; % Plot y1 on the top subplot(2,1,1); plot(x, y1,'bo-.'); xlabel('x values'); ylabel('y values'); % Plot y2 on the bottom subplot(2,1,2); y2 = x + 2; plot(x, y2, 'g+:'); FIGURE Create figure window. FIGURE, by itself, creates a new figure window, and returns its handle. x = [-3-2 -1 0 1 2 3]; y1 = (x.^2) -1; % Plot y1 in the 1 st Figure plot(x, y1,'bo-.'); xlabel('x values'); ylabel('y values'); % Plot y2 in the 2 nd Figure figure y2 = x + 2; plot(x, y2, 'g+:'); Some Useful MATLAB commands who List known variables whos List known variables plus their size help >> help sqrt Help on using sqrt lookfor >> lookfor sqrt Search for keyword sqrt in m-files what >> what a: List MATLAB files in a: clearclear all variables from work space clear x y Clear variables x and y from work space clc Clear the command window Some Useful MATLAB commands what List all m-files in current directory dir List all files in current directory ls Same as dir type test Display test.m in command window delete test Delete test.m cd a: Change directory to a: chdir a: Same as cd pwd Show current directory which test Display directory path to closest test.m 5
MATLAB Relational Operators MATLAB Logical Operators MATLAB supports six relational operators. Less Than < Less Than or Equal <= Greater Than > Greater Than or Equal >= Equal To == Not Equal To ~= MATLAB supports three logical operators. not ~ % highest precedence and & % equal precedence with or or % equal precedence with and MATLAB Logical Functions Matlab Selection Structures MATLAB also supports some logical functions. xor (exclusive or) Ex: xor (a, b) Where a and b are logical expressions. The xor operator evaluates to true if and only if one expression is true and the other is false. True is returned as 1, false as 0. any (x) returns 1 if any element of x is nonzero all (x) returns 1 if all elements of x are nonzero isnan (x) returns 1 at each NaN in x isinf (x) returns 1 at each infinity in x finite (x) returns 1 at each finite value in x An if - elseif - else structure in MATLAB. Note that elseif is one word. if expression1 % is true elseif expression2 % is true else % the default MATLAB Repetition Structures A for loop in MATLAB for x = array for ind = 1:100 b(ind)=sin(ind/10) Alternative: x=0.1:0.1:10; b=sin(x); - Most of the loops can be avoided!!! Question? A while loop in MATLAB while expression while x <= 10 6