Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Tharmarajah Thiruvaran 19-20 March 2007.

Similar presentations


Presentation on theme: "Introduction to Tharmarajah Thiruvaran 19-20 March 2007."— Presentation transcript:

1 Introduction to Tharmarajah Thiruvaran 19-20 March 2007

2 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)

3 Variable and Memory Management
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 19-20 March 2007

4 The Help System 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 19-20 March 2007

5 Vectors and Matrices Vectors (arrays) are defined as
>> w = [1; 2; 4; 5] Matrices (2D arrays) defined similarly >> A = [1,2,3; 4,-5,6; 5,-6,7]

6 Matrices Generation eye - Identity matrix ones - Matrix with all
elements = 1 rand – Random matrix zeros - Matrix with all elements = 0 19-20 March 2007

7 Matrix Index Given: Always starts with 1 (not 0) 19-20 March 2007

8 Matrices Operations Given A and B: Addition Subtraction Product
Transpose 19-20 March 2007

9 The use of “.” – “Element” Operation
Given A: Divide each element of A by 2 Multiply each element of A by 3 Square each element of A 19-20 March 2007

10 MATLAB Math & Assignment Operators
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: /8 = 8\56 - (unary) + (unary) Addition a + b Subtraction a - b Assignment = a = b (assign b to a) 19-20 March 2007

11 Other MATLAB symbols >> prompt
. . . continue statement on next line , separate statements and data % start comment which ends at end of line ; (1) suppress output (2) used as a row separator in a matrix : specify range 19-20 March 2007

12 Matlab Desktop Launch Pad Command Window History >> radius = 50
Ans = 60 Command Window History We all hear about memory: RAM, bits, bytes, words, and more, but how does it all fit together? It all starts with a desire to represent numbers electronically, manipulate them, and store or sometimes print the answers. A computer program is simply a sequence of instructions that manipulate the contents of memory. Most people don’t consider hard disks and CDROMs as “memory” but they are. The key difference is the “permanence” and the “speed” of the memory. Cache and RAM require power to hold their values. Hard disks, CDROM, and Tape retain their contents even when the power is turned off. Cache and RAM require power, but can change values very fast! Faster memory also costs more! 19-20 March 2007

13 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 Precision and accuracy are not the same! A precise answer is not necessarily an accurate answer… One should not demand more precision or accuracy than is necessary… BE CONSISTENT!

14 Matlab Desktop – cont’d
Workspace Command Window Current DIrectory [Instructors: you can spend as much or as little time talking to this picture. Have fun, be a story-teller.] Key points: differences in speed temporary versus permanent Faster memory is more expensive. (Note cost/megabyte for various storage devices.) MATLAB variables are stored in RAM. We use LOAD/SAVE to move data from temporary storage (RAM) to permanent storage (hard disk.) The CPU move memory from RAM to Register for actual computation, then moves the results back to RAM. This picture highlights the differences between memory. CPU registers are the fewest, most precious resources on the computer, and also the FASTEST! The CPU cache either on the CPU (level1) or on the mother board (level 2) are very fast. The RAM (physical or virtual) is where our normal variables are stored. When we create MATLAB arrays, or work with Word Documents, these data are stored in RAM. CDROM, DVD, hard disks are “permanent storage devices.” The input sources interact with memory at different levels, depending on the device. 19-20 March 2007

15 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) We are trying to go from the “MACRO” view of memory, KB, MB, GB, etc. to the micro view. 19-20 March 2007

16 Matlab Editor Access to commands New, Load, Save, etc.
Color keyed text with auto indents Comments tabbed sheets for other files being edited 19-20 March 2007

17 Reserved Words… Matlab has some special (reserved) words that you may not use… switch continue else try catch global persistent break for end if while function return elsif case otherwise 19-20 March 2007

18 Special Variable Description ans default variable name for results beep make sound pi mathematical constant eps smallest number that can be subtracted from 0 to make a negative inf infinity NaN not a number i (or) j imaginary number realmin, realmax smallest & largest positive real numbers bitmax largest positive integer nargin, nargout number of function in (or) out variables varargin variable number of function in arg’s varaout variable number of function out arg’s

19 Matlab Help Let’s bring the memory discussion to MATLAB. Examine the upper left pane on the MATLAB window. Several pieces of memory have been “allocated”, “named” and assigned variables. We used an “assignment statement” (i= 10;) to assign a “value” to a “variable”. On some computers (and in some languages) the memory must first be “allocated” before any values can be assigned. KEY ITEMS TO DISCUSS: A variable is piece of memory that has been given a name. A value is the contents with the variable. THE SCREEN SHOWS: The screen shows the name of the variable, The size of the variable (in elements and bytes), The “class” - what kind of data is stored in the piece of memory 19-20 March 2007

20 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) What if you want to enter different values for radius or length? >> length=5.5; >> radius=2.25; >> volume=pi.*radius^2.*length volume = 19-20 March 2007

21 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 19-20 March 2007

22 Example 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 Type m-file name at prompt to execute m file myscript is called by name >> myscript Enter the length of a cylinder: 8 Now enter the radius: 2.4 Volume of cylinder is: Enter the length of a cylinder: 10 Now enter the radius: 1 Volume of cylinder is: >> 19-20 March 2007

23 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 >> myscript Enter the length of a cylinder: 10 Now enter the radius: 1 Volume of cylinder is: >> whos Name Size Bytes Class length x double array radius x double array volume x double array Grand total is 3 elements using 24 bytes >> >> density=100; >> myscript Enter the length of a cylinder: 10 Now enter the radius: 1 Weight of cylinder is: >> 19-20 March 2007

24 Plot, Hold, Subplot and Figure
Example 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, legend, subplot... x = [ ]; y1 = (x.^2) -1; plot(x, y1,'bo-.'); 19-20 March 2007

25 Plot, Hold, Subplot and Figure
Example 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'); 19-20 March 2007

26 Plot, Hold, Subplot and Figure
Example 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+:'); 19-20 March 2007

27 Plot, Hold, Subplot and Figure
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 Example x = [ ]; 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+:'); 19-20 March 2007

28 Plot, Hold, Subplot and Figure
FIGURE Create figure window. FIGURE, by itself, creates a new figure window, and returns its handle. Example x = [ ]; y1 = (x.^2) -1; % Plot y1 in the 1st Figure plot(x, y1,'bo-.'); xlabel('x values'); ylabel('y values'); % Plot y2 in the 2nd Figure figure y2 = x + 2; plot(x, y2, 'g+:'); 19-20 March 2007

29 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: clear Clear all variables from work space clear x y Clear variables x and y from work space clc Clear the command window 19-20 March 2007

30 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 19-20 March 2007

31 MATLAB Relational Operators
MATLAB supports six relational operators. Less Than < Less Than or Equal <= Greater Than > Greater Than or Equal >= Equal To == Not Equal To ~= 19-20 March 2007

32 MATLAB Logical Operators
MATLAB supports three logical operators. not ~ % highest precedence and & % equal precedence with or or | % equal precedence with and 19-20 March 2007

33 MATLAB Logical Functions
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 19-20 March 2007

34 Matlab Selection Structures
An if - elseif - else structure in MATLAB. Note that elseif is one word. if expression1 % is true % execute these commands elseif expression2 % is true else % the default end 19-20 March 2007

35 MATLAB Repetition Structures
A for loop in MATLAB for x = array for ind = 1:100 b(ind)=sin(ind/10) end Alternative: x=0.1:0.1:10; b=sin(x); - Most of the loops can be avoided!!! A while loop in MATLAB while expression while x <= 10 % execute these commands 19-20 March 2007

36 Questions ? 19-20 March 2007


Download ppt "Introduction to Tharmarajah Thiruvaran 19-20 March 2007."

Similar presentations


Ads by Google