1 / 78

MATLAB:  How do you work with data to solve problems?

MATLAB:  How do you work with data to solve problems?. Fall 2012 Lecture # XX. Mathematical Tools for Quantitative Methods. In today’s technology world, every engineering and computer science discipline uses computers: For computer scientists, as an aid in writing programs.

efigueroa
Download Presentation

MATLAB:  How do you work with data to solve problems?

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. MATLAB:  How do you work with data to solve problems? Fall 2012 Lecture # XX

  2. Mathematical Tools for Quantitative Methods • In today’s technology world, every engineering and computer science discipline uses computers: • For computer scientists, as an aid in writing programs. • For engineers, as a tool to help in the design process, and also to help in solving complex equations. • In most scientific and engineering disciplines, the most useful mathematical equations normally do not have closed solutions. • Often, useful equations are non-linear, perhaps involving second-order differential equations, for which there is no general solution. • This means that many equations are solved using a numerical approach (a fancy way of saying that answers are tried until one works!). • For modern technologists, there are many useful computer tools, normally programs that aid in solving complex equations.

  3. “Too many tools & too little time” • In a course such as ECS 1200, we simply do not have the time to examine many of the available tools. • However, there is one tool, readily available, that would be useful to all undergraduates in ECS that we can survey briefly. • MATLAB

  4. So What Is MATLAB? • A high-performance tool for technical computing, integrating computation, visualization, and programming in such a way that problems and solutions are expressed in familiar mathematical notation. • an “interactive, matrix-based system for algorithm development, GUI Design, data analysis, data visualization, and numeric computation” • A recommended mathematical tool at UTD • Available at the UTD Tech Store

  5. MATLAB High Level Languages such as C, Pascal etc. Assembly What is MATLAB? • MATLAB is an abbreviation for MATrixLABoratory • MATLAB is basically a high level language which has many specialized toolboxes for making things easier for us as engineers and computer scientists • How high?

  6. Why Use MATLAB? • Used mainly for algorithm development and data visualization • Algorithms can be implemented and tested more quickly and easily than with traditional programming languages • Quickly get numerical and graphic answers to matrix and vector related math problems • A way to solve complex numerical problems without actually writing a program • Built-in tools • No complex programming knowledge needed • MATLAB focuses on ease of use and quick development

  7. Some of MATLAB’s Toolboxes Math and Analysis Optimization Requirements Management Interface Statistics Neural Network Symbolic/Extended Math Partial Differential Equations PLS Toolbox Mapping Spline Data Acquisition and Import Data Acquisition Instrument Control Excel Link Portable Graph Object Signal & Image Processing Signal Processing Image Processing Communications Frequency Domain System Identification Higher-Order Spectral Analysis System Identification Wavelet Filter Design Control Design  Control System Fuzzy Logic Robust Control μ-Analysis and Synthesis Model Predictive Control

  8. MATLAB’s Appeal • Interactive code development proceeds incrementally; excellent development and rapid prototyping environment • Basic data element is the auto-indexed array • This allows quick solutions to problems that can be formulated in vector or matrix form • Powerful GUI tools • Large collection of toolboxes: collections of topic-related MATLAB functions that extend the core functionality significantly

  9. MATLAB Example 1 • MATLAB can easily solve families of linear equations. • For example, suppose you need to solve three linear equations for x, y, and z such that: 2x+3y+z=11 x+y+z=6 4x-3y+z=1 • The MATLAB command to solve the equations would be: >> [x,y,z]=solve('2*x+3*y+z=11','x+y+z=6','4*x-3*y+z=1')

  10. MATLAB Example 2 • An even tougher set of equations – say, five linear equations, would be even easier, compared to manual solution: 2v+2w+2x+2y+2z=30 2v+2w+2x+y-z=19 4x+y-z=3 v+w+x-y-z=5 5v-w+2x+2y+2z=27 • The same “solve” function is used. Equations are written as before, using “*” to denote multiplication, quotes (‘’) to denote the range of each equation, and a comma separator.

  11. MATLAB Summary • MATLAB is a complex program that is an excellent mathematical tool for solving complex science and engineering problems. • In general, it is so complex that it takes some “getting used to.” You cannot just plunge into it today and expect to be a master in about ten minutes. • However, with a little work, you can master its intricacies and become a MATLAB master. • Because the student price is so good, and because you will be using MATLAB in some of your advanced UG courses, it would be a good idea to start learning now!

  12. MATLAB Screen Command Window type commands Current Directory View folders and m-files Workspace View program variables Double click on a variable to see it in the Array Editor Command History view past commands save a whole session using diary

  13. Some MATLAB Development Windows • Command Window: where you enter commands • Command History: running history of commands which is preserved across MATLAB sessions • Current directory: current location for session • Workspace: GUI for viewing, loading and saving MATLAB variables • Array Editor: GUI for viewing and/or modifying contents of MATLAB variables (openvarvarname or double-click the array’s name in the Workspace) • Editor/Debugger: text editor, debugger; editor works with file types in addition to .m (MATLAB “m-files”)

  14. Entering Commands and Expressions • MATLAB retains your previous keystrokes. • Use the up-arrow key to scroll back back through the commands. • Press the key once to see the previous entry, and so on. • Use the down-arrow key to scroll forward. Edit a line using the left- and right-arrow keys the Backspace key, and the Delete key. • Press the Enter key to execute the command.

  15. A video introduction: • A Five Minute Introduction to MATLAB

  16. Example Session >> 8/10 ans = 0.8000 >> 5*ans ans = 4 >> r=8/10 r = 0.8000 >> r r = 0.8000 >> s=20*r s = 16

  17. More Examples >> 8 + 3*5 ans = 23 >> 8 + (3*5) ans = 23 >>(8 + 3)*5 ans = 55 >>4^2­12­8/4*2 ans = 0 >>4^2­12­ 8/(4*2) ans = 3

  18. …and some more examples >> 3*4^2 + 5 ans = 53 >>(3*4)^2 + 5 ans = 149 >>27^(1/3) + 32^(0.2) ans = 5 >>27^(1/3) + 32^0.2 ans = 5 >>27^1/3 + 32^0.2 ans = 11

  19. int a; double b; float c; Variables • No need for types. i.e., • All variables are created with double precision unless specified and they are matrices. • After these statements, the variables are 1x1 matrices with double precision Example: >>x=5; >>x1=2;

  20. Variable Basics >> 16 + 24 ans = 40 >> product = 16 * 23.24 product = 371.84 >> product = 16 *555.24; >> product product = 8883.8 no declarations needed mixed data types semi-colon suppresses output of the calculation’s result

  21. Variable Basics >> clear >> product = 2 * 3^3; >> comp_sum = (2 + 3i) + (2 - 3i); >> show_i = i^2; >> save three_things >> clear >> load three_things >> who Your variables are: comp_sum product show_i >> product product = 54 >> show_i show_i = -1 clear removes all variables; clear x y removes only x and y complex numbers (i or j) require no special handling save/load are used to retain/restore workspace variables use home to clear screen and put cursor at the top of the screen

  22. Special variables and constants Numeric display formats

  23. >> A = [16 3; 5 10] A = 16 3 5 10 Matrices & Vectors • All (almost) entities in MATLAB are matrices • Easy to define: • Use ‘,’ or ‘ ’ to separate row elements -- use ‘;’ to separate rows

  24. Matrix: >> A=[1 2; 3 4]; >> A' ans = 1 3 2 4 Vector : >> a=[1 2 3]; >> a' 1 2 3 Creating Vectors and Matrices >> A = [16 3; 5 10] A = 16 3 5 10 >> B = [3 4 5 6 7 8] B = 3 4 5 6 7 8 • Define • Transpose

  25. Creating Vectors Create vector with equally spaced intervals >> x=0:0.5:pi x = 0 0.5000 1.0000 1.5000 2.0000 2.5000 3.0000 Create vector with n equally spaced intervals >> x=linspace(0, pi, 7) x = 0 0.5236 1.0472 1.5708 2.0944 2.6180 3.1416 Equal spaced intervals in logarithm space >> x=logspace(1,2,7) x = 10.0000 14.6780 21.5443 … 68.1292 100.0000 Note: MATLAB uses pi to represent , uses i or j to represent imaginary unit

  26. Creating Matrices • zeros(m, n):matrix with all zeros • ones(m, n): matrix with all ones. • eye(m, n): the identity matrix • rand(m, n): uniformly distributed random • randn(m, n): normally distributed random • magic(m): square matrix whose elements have the same sum, along the row, column and diagonal. • pascal(m) : Pascal matrix.

  27. Matrix operations • ^:exponentiation • *: multiplication • /: division • \: left division. The operation A\Bis effectively the same as INV(A)*B, although left division is calculated differently and is much quicker. • +: addition • -: subtraction

  28. Matrices Operations Given A and B: Addition Subtraction Transpose Product

  29. Array Operations • Evaluated element by element .' : array transpose (non-conjugated transpose) .^ : array power .* : array multiplication ./ : array division • Very different from Matrix operations >> A=[1 2;3 4]; >> B=[5 6;7 8]; >> A*B 19 22 43 50 But: >> A.*B 5 12 21 32

  30. The use of “.” – “Element” Operation A = [1 2 3; 5 1 4;3 2 1] A = 1 2 3 5 1 4 3 2 -1 b = x .* y b= 3 8 -3 c = x . / y c= 0.33 0.5 -3 d = x .^2 d= 1 4 9 x = A(1,:) x= 1 2 3 y = A(3 ,:) y= 3 4 -1

  31. Some Built-in functions • mean(A):mean value of a vector • max(A), min (A): maximum and minimum. • sum(A): summation. • sort(A): sorted vector • median(A): median value • std(A): standard deviation. • det(A) : determinant of a square matrix • dot(a,b): dot product of two vectors • Cross(a,b): cross product of two vectors • Inv(A): Inverse of a matrix A • length(A): number of values in an array

  32. Operators (relational, logical) • == Equal to • ~= Not equal to • < Strictly smaller • > Strictly greater • <= Smaller than or equal to • >= Greater than equal to • & And operator • | Or operator

  33. Indexing Matrices n A = 0.9501 0.6068 0.4231 0.2311 0.4860 0.2774 Given the matrix: Then: A(1,2) = 0.6068 A(:,1) = [0.9501 0.2311 ] A(1,2:3)=[0.6068 0.4231] m 1:m

  34. Adding Elements to a Vector or a Matrix >> C=[1 2; 3 4] C= 1 2 3 4 >> C(3,:)=[5 6]; C= 1 2 3 4 5 6 >> D=linspace(4,12,3); >> E=[C D’] E= 1 2 4 3 4 8 5 6 12 >> A=1:3 A= 1 2 3 >> A(4:6)=5:2:9 A= 1 2 3 5 7 9 >> B=1:2 B= 1 2 >> B(5)=7; B= 1 2 0 0 7

  35. Flow Control • if • for • while • break • ….

  36. Some Dummy Examples if ((a>3) & (b==5)) Some MATLAB Commands; end if (a<3) Some MATLAB Commands; elseif (b~=5) Some MATLAB Commands; end if (a<3) Some MATLAB Commands; else Some MATLAB Commands; end Control Structures • If Statement Syntax if (Condition_1) MATLAB Commands elseif (Condition_2) MATLAB Commands elseif (Condition_3) MATLAB Commands else MATLAB Commands end

  37. Some Dummy Examples for i=1:100 Some MATLAB Commands; end for j=1:3:200 Some MATLAB Commands; end for m=13:-0.2:-21 Some MATLAB Commands; end for k=[0.1 0.3 -13 12 7 -9.3] Some MATLAB Commands; end Control Structures • For loop syntax for i=Index_Array MATLAB Commands end

  38. Control Structures • While Loop Syntax while (condition) MATLAB Commands end Dummy Example while ((a>3) & (b==5)) Some MATLAB Commands; end

  39. You can perform operations in MATLAB in two ways: 1. In the interactive mode, in which all commands are entered directly in the Command window, or 2. By running a MATLAB program stored in script file. This type of file contains MATLAB commands, so running it is equivalent to typing all the commands—one at a time—at the Command window prompt. You can run the file by typing its name at the Command window prompt.

  40. Scripts and Functions • Scripts do not accept input arguments, nor do they produce output arguments. Scripts are simply MATLAB commands written into a file. They operate on the existing workspace. • Functions accept input arguments and produce output variables. All internal variables are local to the function and commands operate on the function workspace. • A file containing a script or function is called an m-file • If duplicate functions (names) exist, the first in the search path (from path command) is executed.

  41. Use of M-File Click to create a new M-File • Extension “.m” • A text file containing script or function or program to run

  42. Save file as Denem430.m Use of M-File If you include “;” at the end of each statement, result will not be shown immediately

  43. Writing User Defined Functions • Functions are m-files which can be executed by specifying some inputs and supply some desired outputs. • The code telling the MATLAB that an m-file is actually a function is • You should write this command at the beginning of the m-file and you should save the m-file with a file name same as the function name function out1=functionname(in1) function out1=functionname(in1,in2,in3) function [out1,out2]=functionname(in1,in2)

  44. Same Name Writing User Defined Functions • Examples • Write a function : out=squarer (A, ind) • Which takes the square of the input matrix if the input indicator is equal to 1 • And takes the element by element square of the input matrix if the input indicator is equal to 2

  45. Writing User Defined Functions • Another function which takes an input array and returns the sum and product of its elements as outputs • The function sumprod(.) can be called from command window or an m-file as

  46. Keep in mind when using script files: 1. The name of a script file must begin with a letter, and may include digits and the underscore character, up to 63 characters. 2. Do not give a script file the same name as a variable. 3. Do not give a script file the same name as a MATLAB command or function. You can check to see if a command, function or file name already exists by using the exist command.

  47. MATLAB Graphics x = 0:pi/100:2*pi; y = sin(x); plot(x,y) xlabel('x = 0:2\pi') ylabel('Sine of x') title('Plot of the Sine Function')

  48. A graphics window showing a plot.

More Related