### Create a StudySoup account

#### Be part of our community, it's free to join!

Already have a StudySoup account? Login here

# BEG SCI COMPUTING AMATH 301

UW

GPA 3.59

### View Full Document

## 122

## 0

## Popular in Course

## Popular in Applied Mathematics

This 45 page Class Notes was uploaded by Mossie Pfannerstill V on Wednesday September 9, 2015. The Class Notes belongs to AMATH 301 at University of Washington taught by Staff in Fall. Since its upload, it has received 122 views. For similar materials see /class/192280/amath-301-university-of-washington in Applied Mathematics at University of Washington.

## Reviews for BEG SCI COMPUTING

### What is Karma?

#### Karma is the currency of StudySoup.

#### You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 09/09/15

MATLAB 7 Getting Started Guide MathWorkS39 Acatuatin apacl enginasn39n g th at g andso39enne EDD How to Contact MathWorks Web Newsgroup wwwmathworkscom compsoftsysmatlab wwwmathworkscomcontactTShtml Techr calf3upport Product enhancement suggestions Bug reports suggest mathworkscom bugs mathworkscom doc mathworkscom service mathworkscom info mathworkscom 5086477000 Phone Documentation error reports Order status license renewals passcodes Sales pricing and general information 5086477001 Fax The MathWorks Inc 3 Apple Hill Drive Natick MA 017602098 For contact information about worldwide offices see the MathWorks Web site MATLAB Getting Started Guide COPYRIGHT 1984 20 10 by The MathWorks Inc The software described in this document is furnished under a license agreement The software may be used or copied only under the terms of the license agreement No part of this manual may be photocopied or reproduced in any form without prior written consent from The MathWorks Inc FEDERAL ACQUISITION This provision applies to all acquisitions of the Program and Documentation by for or through the federal government of the United States By accepting delivery of the Program or Documentation the government hereby agrees that this software or documentation qualifies as commercial computer software or commercial computer software documentation as such terms are used or defined in FAR 12212 DFARS Part 22772 and DFARS 2522277014 Accordingly the terms and conditions of this Agreement and only those rights specified in this Agreement shall pertain to and govern the use modification reproduction release performance display and disclosure of the Program and Documentation by the federal government or other entity acquiring for or through the federal government and shall supersede any con icting contractual terms or conditions If this License fails to meet the government s needs or is inconsistent in any respect with federal procurement law the government agrees to return the Program and Documentation unused to The MathWorks Inc Trademarks MATLAB and Simulink are registered trademarks of The MathWorks Inc See wwwmathworks comtrademarks for a list of additional trademarks Other product or brand names may be trademarks or registered trademarks of their respective holders Patents MathWorks products are protected by one or more US patents Please see wwwmathworks compatents for more information Revision History December 1996 First printing For MATLAB 5 May 1997 Second printing For MATLAB 51 September 1998 Third printing For MATLAB 58 September 2000 Fourth printing Revised for MATLAB 6 Release 12 June 2001 Online only Revised for MATLAB 61 Release 121 July 2002 Online only Revised for MATLAB 65 Release 18 August 2002 Fifth printing Revised for MATLAB 65 June 2004 Sixth printing Revised for MATLAB 70 Release 14 October 2004 Online only Revised for MATLAB 701 Release 14SP 1 March 2005 Online only Revised for MATLAB 704 Release 14SP2 June 2005 Seventh printing Minor revision for MATLAB 704 Release 14SP2 September 2005 Online only Minor revision for MATLAB 71 Release 14SP8 March 2006 Online only Minor revision for MATLAB 72 Release 2006a September 2006 Eighth printing Minor revision for MATLAB 78 Release 2006b March 2007 Ninth printing Minor revision for MATLAB 74 Release 2007a September 2007 Tenth printing Minor revision for MATLAB 75 Release 2007b March 2008 Eleventh printing Minor revision for MATLAB 76 Release 2008a October 2008 Twelfth printing Minor revision for MATLAB 77 Release 2008b March 2009 Thirteenth printing Minor revision for MATLAB 78 Release 2009a September 2009 Fourteenth printing Minor revision for MATLAB 79 Release 2009b March 2010 Fifteenth printing Minor revision for MATLAB 710 Release 2010a September 2010 Sixteenth printing Revised for MATLAB 711 R2010b Getting Started Introduction Product Overview 1 2 Overview of the MATLAB Environment 1 2 The MATLAB System 1 3 Documentation 1 5 Starting and Quitting the MATLAB Program 1 7 Starting a MATLAB Session 1 7 Quitting the MATLAB Program 1 8 Matrices and Arrays Z Matrices and Magic Squares 2 2 About Matrices 2 2 Entering Matrices 2 4 sum transpose and diag 2 5 Subscripts 2 7 The Colon Operator 2 8 The magic Function 2 9 Expressions 2 11 Variables 2 11 Numbers 2 12 Operators 2 13 vi Contents Functions 2 14 Examples of Expressions 2 15 Working with Matrices 2 17 Generating Matrices 2 17 The load Function 2 18 Saving Code to a File 2 18 Concatenation 2 19 Deleting Rows and Columns 2 20 More About Matrices and Arrays 2 21 Linear Algebra 2 21 Arrays 2 25 Multivariate Data 2 27 Scalar Expansion 2 28 Logical Subscripting 2 28 The find Function 2 29 Controlling Connnand Window Input and Output 2 31 3 The format Function 2 31 Suppressing Output 2 32 Entering Long Statements 2 33 Command Line Editing 2 33 Graphics Overview of Plotting 3 2 Plotting Process 3 2 Graph Components 3 6 Figure Tools 3 7 Arranging Graphs Within a Figure 3 14 Choosing a Type of Graph to Plot 3 15 Editing Plots 3 23 Plot Edit Mode 3 23 Using Functions to Edit Graphs 3 28 Some Ways to Use Plotting Tools 3 29 Plotting Two Variables with Plotting Tools 3 29 Changing the Appearance of Lines and Markers 3 32 Adding More Data to the Graph 3 33 Changing the Type of Graph 3 36 Modifying the Graph Data Source 3 38 Preparing Graphs for Presentation 3 43 Annotating Graphs for Presentation 3 43 Printing the Graph 3 48 Exporting the Graph 3 52 Using Basic Plotting Functions 3 56 Creating a Plot 3 56 Plotting Multiple Data Sets in One Graph 3 57 Specifying Line Styles and Colors 3 58 Plotting Lines and Markers 3 59 Graphing Imaginary and Complex Data 3 61 Adding Plots to an Existing Graph 3 62 Figure Windows 3 63 Displaying Multiple Plots in One Figure 3 64 Controlling the Axes 3 66 Adding Axis Labels and Titles 3 67 Saving Figures 3 68 Creating Mesh and Surface Plots 3 72 About Mesh and Surface Plots 3 72 Visualizing Functions of Two Variables 3 72 Plotting Image Data 3 80 About Plotting Image Data 3 80 Reading and Writing lmages 3 81 Printing Graphics 3 82 Overview of Printing 3 82 Printing from the File Menu 3 82 Exporting the Figure to a Graphics File 3 83 Using the Print Command 3 83 Understanding Handle Graphics Objects 3 85 Using the Handle 3 85 viii Contents 4 Graphics Objects 3 86 Setting Object Properties 3 88 Specifying the Axes or Figure 3 91 Finding the Handles of Existing Objects 3 92 Programming Flow Control 4 2 Conditional Control 7 if else switch 4 2 Loop Control 7 for while continue break 4 5 Error Control 7 try catch 4 7 Program Termination i return 4 8 Other Data Structures 4 9 Multidimensional Arrays 4 9 Cell Arrays 4 11 Characters and Text 4 13 Structures 4 16 Scripts and Functions 4 20 Overview 4 20 Scripts 4 21 Functions 4 22 Types ofFunctions 4 24 Global Variables 4 26 Passing String Arguments to Functions 4 27 The eval Function 4 28 Function Handles 4 28 Function Functions 4 29 Vectorization 4 31 Preallocation 4 32 Object Oriented Programming 4 33 MATLAB Classes and Objects 4 33 Learn About Defining MATLAB Classes 4 33 Data Analysis 5 Introduction 5 2 Preprocessing Data 5 3 Overview 5 3 Loading the Data 5 3 Missing Data 5 3 Outliers 5 4 Smoothing andFiltering 5 6 Summarizing Data 5 10 Overview 5 10 Measures of Location 5 10 Measures of Scale 5 11 Shape ofa Distribution 5 11 Visualizing Data 5 14 Overview 5 14 2D Scatter Plots 5 14 8D Scatter Plots 5 16 Scatter Plot Arrays 5 18 Exploring Data in Graphs 5 19 Modeling Data 5 27 Overview 5 27 Polynomial Regression 5 27 General Linear Regression 5 28 Creating Graphical User Interfaces 6 What Is GUIDE 6 2 Laying Out a GUI 6 3 Starting GUIDE 6 3 X Contents The Layout Editor 6 4 Programming a GUI Desktop Tools and Development Environment 7 Desktop Overview 7 2 Introduction to the Desktop 7 2 Arranging the Desktop 7 3 Start Button 7 3 Command Window and Command History 7 5 Command Window 7 5 Command History 7 6 Getting Help 7 7 Ways to Get Help 7 7 Accessing Documentation Examples and Demos Using the Help Browser 7 9 Searching for Documentation and Demos 7 11 Browsing for Documentation and Demos 7 15 Running Demos and Code in Examples 7 16 Workspace Browser and Variable Editor 7 20 Workspace Browser 7 20 Variable Editor 7 21 Managing Files in MATLAB 7 23 How MATLAB Helps You Manage Files 7 23 Making Files Accessible to MATLAB 7 23 Using the Current Folder Browser to Manage Files 7 24 More Ways to Manage Files 7 26 Finding and Getting Files Created by Other Users File Exchange 7 27 Editor 7 29 Editing MATLAB Code Files 7 29 Identifying Problems and Areas for Improvement 7 31 Publishing MATLAB Code Files 7 34 Improving and Tuning Your MATLAB Programs 7 38 Finding Errors Using the Code Analyzer Report 7 38 Improving Performance Using the Profiler 7 40 Externallnterfaces 8 Programing Interfaces 8 2 Call MATLAB Software from CC and Fortran Programs 8 2 Call CC and Fortran Programs from MATLAB Command Line 8 2 Call Sun Java Commands from MATLAB Command Line 8 3 Call Functions in Shared Libraries 8 3 Import and Export Data 8 3 Interface to NET Framework 8 4 Component Object Model Interface 8 5 Web Services 8 6 Serial Port Interface 8 7 Index Xi Contents Getting Started The MATLAB highperformance language for technical computing integrates computation visualization and programming in an easytouse environment where problems and solutions are expressed in familiar mathematical notation You can watch the Getting Started with MATLAB video demo for an overview of the major functionality If you have an active Internet connection you can also watch the Working in the Development Environment video demo and the Writing a MATLAB Program video demo This collection includes the following topics Chapter 1 Introduction p 11 Chapter 2 Matrices and Arrays p 21 Chapter 3 Graphics p 31 Chapter 4 Programming p 41 Chapter 5 Data Analysis p 51 Chapter 6 Creating Graphical User Interfaces p 61 Chapter 7 Desktop Tools and Development Environment p 7 1 Chapter 8 External Interfaces 13 81 Describes the components of the MATLAB system How to use MATLAB to generate matrices and perform mathematical operations on matrices How to plot data annotate graphs and work with images How to use MATLAB to create scripts and functions how to construct and manipulate data structures How to set up a basic data analysis Introduces GUIDE the MATLAB graphical user interface development environment Information about tools and the MATLAB desktop Introduces external interfaces available in MATLAB software Gettinq Started A printable version PDF of this documentation is available on the WebiMATLAB Getting Started Guide For tutorial information about any of the topics covered in this collection see the corresponding sections in the MATLAB documentation For reference information about MATLAB functions see the MATLAB Function Reference Introduction I Product Overviewquot on page 12 I Documentation on page 15 I Starting and Quitting the MATLAB Programquot on page 17 Product Overview In this section Overview of the MATLAB Environmentquot on page 12 The MATLAB Systemquot on page 18 Overview of the MATLAB Environment MATLAB is a highlevel technical computing language and interactive environment for algorithm development data visualization data analysis and numeric computation Using the MATLAB product you can solve technical computing problems faster than with traditional programming languages such as C C and Fortran You can use MATLAB in a wide range of applications including signal and image processing communications control design test and measurement financial modeling and analysis and computational biology Addon toolboxes collections of specialpurpose MATLAB functions available separately extend the MATLAB environment to solve particular classes of problems in these application areas MATLAB provides a number of features for documenting and sharing your work You can integrate your MATLAB code with other languages and applications and distribute your MATLAB algorithms and applications Features include I Highlevel language for technical computing I Development environment for managing code files and data I Interactive tools for iterative exploration design and problem solving I Mathematical functions for linear algebra statistics Fourier analysis filtering optimization and numerical integration I 2D and 8D graphics functions for visualizing data I Tools for building custom graphical user interfaces Product Overview I Functions for integrating MATLAB based algorithms with external applications and languages such as C C Fortran JavaTM COM and Microsoft Excel The MATLAB System The MATLAB system consists of these main parts Desktop Tools and Development Environment This part of MATLAB is the set of tools and facilities that help you use and become more productive with MATLAB functions and files Many of these tools are graphical user interfaces It includes the MATLAB desktop and Command Window an editor and debugger a code analyzer and browsers for viewing help the workspace and folders Mathematical Function Library This library is a vast collection of computational algorithms ranging from elementary functions like sum sine cosine and complex arithmetic to more sophisticated functions like matrix inverse matrix eigenvalues Bessel functions and fast Fourier transforms The Language The MATLAB language is a highlevel matrixarray language with control flow statements functions data structures inputoutput and objectoriented programming features It allows both programming in the smallquot to rapidly create quick programs you do not intend to reuse You can also do programming in the largequot to create complex application programs intended for reuse Graphics MATLAB has extensive facilities for displaying vectors and matrices as graphs as well as annotating and printing these graphs It includes highlevel functions for t quot 39 and thr quot 39 data 39 quot quot image A 39 39 quot and pi 39 graphics It also includes lowlevel functions that allow you to fully customize the appearance of graphics as well as to build complete graphical user interfaces on your MATLAB applications Introduction Exteran Interfaces The external interfaces library allows you to write CC and Fortran programs that interact with MATLAB It includes facilities for calling routines from MATLAB dynamic linking for calling MATLAB as a computational engine and for reading and writing MATfiles Documentation The MATLAB program provides extensive documentation in both printable and HTML format to help you learn about and use all of its features If you are a new user begin with this Getting Started guide It covers all the primary MATLAB features at a high level including many examples To view the online documentation select Help gt Product Help in MATLAB Online help appears in the Help browser providing taskoriented and reference information about MATLAB features For more information about using the Help browser see Getting Helpquot on page 77 The MATLAB documentation is organized into these main topics I Desktop Tools and Development Environment 7 Startup and shutdown arranging the desktop and using tools to become more productive with MATLAB I Data Import and Export 7 Retrieving and storing data memorymapping and accessing lnternet files Mathematics 7 Mathematical operations I Data Analysis 7 Data analysis including data fitting Fourier analysis and timeseries tools I Programming Fundamentals i The MATLAB language and how to develop MATLAB applications ObjectOriented Programming 7 Designing and implementing MATLAB classes I Graphics 7 Tools and techniques for plotting graph annotation printing and programming with Handle Graphics objects I 8D Visualization i Visualizing surface and volume data transparency and viewing and lighting techniques Creating Graphical User Interfaces 7 GUIbuilding tools and how to write callback functions I External Interfaces 7 MEXfiles the MATLAB engine and interfacing to Sun MicrosystemsTM Java software Microsoft NET Framework COM Web services and the serial port Introduction There is reference documentation for all MATLAB functions I Function Reference 7 Lists all MATLAB functions listed in categories or alphabetically I Handle Graphics Property Browser 7 Provides easy access to descriptions of graphics object properties I CC and Fortran API Reference 7 Covers functions used by the MATLAB external interfaces providing information on syntax in the calling language description arguments return values and examples The MATLAB online documentation also includes I Examples 7 An index of examples included in the documentation I Release Notes 7 New features compatibility considerations and bug reports for current and recent previous releases I Printable Documentation 7 PDF versions of the documentation suitable for printing In addition to the documentation you can access demos for each product from the Help browser Run demos to learn about key functionality of MathWorks products and tools Startinq and Quittinq the MATLAB Proqrqm Starting and Quitting the MATLAB Program In this section Starting a MATLAB Sessionquot on page 17 Quitting the MATLAB Programquot on page 18 Starting a MATLAB Session On Microsoft Windows platforms start the MATLAB program by doubleclicking the MATLAB shortcut 9 on your Windows desktop On Apple Macintosh platforms start MATLAB by doubleclicking the MATLAB icon in the Applications folder On UNIX platforms start MATLAB by typing matlab at the operating system prompt When you start MATLAB by default MATLAB automatically loads all the program files provided by MathWorks for MATLAB and other MathWorks products You do not have to start each product you want to use There are alternative ways to start MATLAB and you can customize MATLAB startup For example you can change the folder in which MATLAB starts or automatically execute MATLAB statements upon startup For More Information See Startup and Shutdownquot in the Desktop Tools 1 rw 1 and p w numueut The Desktop When you start MATLAB the desktop appears containing tools graphical user interfaces for managing files variables and applications associated with MATLAB The following illustration shows the default desktop You can customize the arrangement of tools and documents to suit your needs For more information 1 mroducnon about the desktop too1s see Chapter 7 quotDesktop Tools and Development Ehvmhmeht Menus ehange Enter MATLAB minimize dependlng 0quot statements at the the tool you usin Quilting the MATLAB Program To end your MATLAB Sesslon se1ect File gt Exit MATLAB th the desktop or type qtut th the Command Wmdow You can run a scrlpt le named 1n1shm each time MATLAB qults that for example executes functions to save the workspace Q 9 MATLAEI can dxsplay a can rmatmn dmlag bax befare quxmng Ta set ths Men Select me gt peereeeneee gt General gt cennmmen melege and select the check bax far Cnn rm befnre exiting MATLAB Mnnna Ave vau suve yau Wanna exn wene57 r Du nm smmms Pvamm Egam me ForMore Information See quotQummg the MATLAEI Fragramquotmthe Desktap Taals and Develapment Enmmnment dacumentatmn 1 Introduction 110 Matrices and Arrays You can watch the Getting Started with MATLAB video demo for an overview of the major functionality Matrices and Magic Squaresquot on page 22 Expressions on page 211 Working with Matricesquot on page 217 More About Matrices and Arraysquot on page 221 Controlling Command Window Input and Outputquot on page 281 2 Matrices and Arrays Matrices and Magic Squares In this section About Matricesquot on page 22 Entering Matricesquot on page 24 sum transpose and diagquot on page 25 Subscripts on page 27 The Colon Operatorquot on page 28 The magic Functionquot on page 29 About Matrices In the MATLAB environment a matrix is a rectangular array of numbers Special meaning is sometimes attached to 1by1 matrices which are scalars and to matrices with only one row or column which are vectors MATLAB has other ways of storing both numeric and nonnumeric data but in the beginning it is usually best to think of everything as a matrix The operations in MATLAB are designed to be as natural as possible Where other programming languages work with numbers one at a time MATLAB allows you to work with entire matrices quickly and easily A good example matrix used throughout this book appears in the Renaissance engraving Melencolia l by the German artist and amateur mathematician Albrecht DUrer This Image is lled wnh mathematical symbahsm and 1f yau laak carefully yau mu see 5 mx m the upper ngm mrner This memx is knawn as a mag square and was believed by many m Durer39s ume m ave genuinely magical pmperues n dues tum nut m have same fascinating characteristics warth explanng 2 Mamas and Ana r Entering Matrices The best way lsrysu La get started wrtn MATLAEI ls La learn haw La handle ample matrrees Start MATLAE and allaw alans wrtn each ex Yau can enter matrrees rnts MATLAEI In several dl 39erent ways Enter an exnlrert lrst af elem ts Laad matrrees ram external data les Generate matrrees usms bullt In lunetmns Create matrrees wrth yaur awn lunetmns andsave Lhemm lrles Start by enterrns Durer39s matrrx as a lrst af rts elements Yau anly have La allaw a lew bash canventmns Separate the elements afamw wrtn blanks ar cammas Use a semlcalan dlcate the end af each r w ts In Surmundthe entrre lrst af elements wrtn Square brackets 1 Ta enter Durer39s matrnr sxmnly type In the Cammand Wmdaw AI163213510HB S712415141 Matrices and M01qu Squares MATLAB displays the matrix you just entered A 16 3 2 13 5 1O 11 8 9 6 7 12 4 15 14 1 This matrix matches the numbers in the engraving Once you have entered the matrix it is automatically remembered in the MATLAB workspace You can refer to it simply as A Now that you have A in the workspace take a look at what makes it so interesting Why is it magic sum transpose and diag You are probably already aware that the special properties of a magic square have to do with the various ways of summing its elements If you take the sum along any row or column or along either of the two main diagonals you will always get the same number Let us verify that using MATLAB The first statement to try is sum A MATLAB replies with ans 34 34 34 34 When you do not specify an output variable MATLAB uses the variable ans short for answer to store the results of a calculation You have computed a row vector containing the sums of the columns of A Each of the columns has the same sum the magic sum 34 How about the row sums MATLAB has a preference for working with the columns of a matrix so one way to get the row sums is to transpose the matrix compute the column sums of the transpose and then transpose the result For an additional way that avoids the double transpose use the dimension argument for the sum function MATLAB has two transpose operators The apostrophe operator eg A39 performs a complex conjugate transposition lt flips a matrix about its main 2 Matrices and Arrays diagonal and also changes the sign of the imaginary component of any complex elements of the matrix The dotapostrophe operator eg A 39 transposes Without affecting the sign of complex elements For matrices containing all real elements the two operators return the same result So A produces ans 16 9 4 1O 6 15 2 11 7 14 13 8 12 1 and sumA39 39 produces a column vector containing the row sums ans 34 34 34 34 The sum of the elements on the main diagonal is obtained with the sum and the diag functions diagA produces ans 16 1O Matrices and quic Squares and sumdiagA produces ans 34 The other diagonal the socalled antidiagonal is not so important mathematically so MATLAB does not have a readymade function for it But a function originally intended for use in graphics fliplr flips a matrix from left to right sumdiagfliplr A ans 34 You have verified that the matrix in Durer s engraving is indeed a magic square and in the process have sampled a few MATLAB matrix operations The following sections continue to use this matrix to illustrate additional MATLAB capabilities Subscripts The element in row i and column j ofA is denoted by Aij For example A4 2 is the number in the fourth row and second column For the magic square A4 2 is 15 So to compute the sum of the elements in the fourth column of A type A1y4 A2y4 A3y4 A4y4 This subscript produces ans 34 but is not the most elegant way of summing a single column It is also possible to refer to the elements of a matrix with a single subscript A k A single subscript is the usual way of referencing row and column vectors However it can also apply to a fully two dimensional matrix in 2 Matrices and Arrays which case the array is regarded as one long column vector formed from the columns of the original matrix So for the magic square A8 is another way of referring to the value 15 storedin A4 2 If you try to use the value of an element outside of the matrix it is an error t A45 Index exceeds matr ix dimensions Conversely if you store a value in an element outside of the matrix the size increases to accommodate the newcomer X A X45 17 X 16 3 2 13 O 5 1O 11 8 O 9 6 7 12 O 4 15 14 1 17 The Colon Operator The colon is one of the most important MATLAB operators It occurs in several different forms The expression 1 10 is a row vector containing the integers from 1 to 10 1 2 3 4 5 6 7 8 9 10 To obtain nonunit spacing specify an increment For example 100 750 is 100 93 86 79 72 65 58 51 and Opi4pi Matrices and quic Squares 0 07854 15708 23562 31416 Subscript expressions involving colons refer to portions of a matrix A1kj is the first k elements of the jth column of A Thus sumA144 computes the sum of the fourth column However there is a better way to perform this computation The colon by itself refers to all the elements in a row or column of a matrix and the keyword end refers to the last row or column Thus sumA end computes the sum of the elements in the last column of A ans 34 Why is the magic sum for a 4hy4 square equal to 84 If the integers from 1 to 16 are sorted into four groups with equal sums that sum must he sum1 16 4 which of course is ans 34 The magic Function MATLAB actually has a builtin function that creates magic squares of almost any size Not surprisingly this function is named magic 2 Matrices and Arrays B magic4 B 16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1 This matrix is almost the same as the one in the DUrer engraving and has all the same magic properties the only difference is that the two middle columns are exchange To make this B into Durer s A swap the two middle columns A B13 2 4 This subscript indicates thatifor each of the rows of matrix Bireorder the elements in the order 1 3 2 4 It produces A 16 3 2 13 5 1O 11 8 9 6 7 12 4 15 14 1 Expressions Expressions In this section Variables on page 211 Numbers on page 212 Operators on page 213 Functions on page 214 Examples of Expressionsquot on page 215 Variables Like most other programming languages the MATLAB language provides mathematical expressions but unlike most programming languages these expressions involve entire matrices MATLAB does not require any type declarations or dimension statements When MATLAB encounters a new variable name it automatically creates the variable and allocates the appropriate amount of storage If the variable already exists MATLAB changes its contents and if necessary allocates new storage For example numstudents 25 creates a 1by1 matrix named numstudents and stores the value 25 in its single element To view the matrix assigned to any variable simply enter the variable name Variable names consist ofa letter followedby any number ofletters digits or underscores MATLAB is case sensitive it distinguishes between uppercase and lowercase letters A and a are not the same variable Although variable names can be of any length MATLAB uses only the first N characters of the name where N is the number returned by the function namelengthmax and ignores the rest Hence it is important to make each variable name unique in the first N characters to enable MATLAB to distinguish variables 2 Matrices and Arrays 22 namelengthmax 63 The genvar name function can be useful in creating variable names that are both valid and unique Numbers MATLAB uses conventional decimal notation with an optional decimal point and leading plus or minus sign for numbers Scientific notation uses the letter e to specify a poweroften scale factor lmaginary numbers use either i or j as a suffix Some examples of legal numbers are 3 99 00001 96397238 160210e20 602252623 1i 314159j 3651 MATLAB stores all numbers internally using the long format specified by the IEEE floatingpoint standard Floatingpoint numbers have a finite precision of roughly 16 significant decimal digits and a finite range of roughly 107308 to 1030839 Numbers represented in the double format have a maximum precision of 52 bits Any double requiring more bits than 52 loses some precision For example the following code shows two unequal values to be equal because they are both truncated X 36028797018963968 y 36028797018963972 Xy lntegers have available precisions of 8bit 16bit 82bit and 64bit Storing the same numbers as 64bit integers preserves precision x uint6436028797018963968 y uint6436028797018963972 X y ans Expressions The section Avoiding Common Problems with FloatingPoint Arithmetic gives a few of the examples showing how lEEE floatingpoint arithmetic affects computations in MATLAB For more examples and information see Technical Note 1108 7 Common Problems with FloatingPoint Arithmetic MATLAB software stores the real and imaginary parts of a complex number It handles the magnitude of the parts in different ways depending on the context For instance the so r t function sorts based on magnitude and resolves ties by phase angle sor t34i 43i ans 40000 300001 30000 400001 This is because of the phase angle angle34i ans 09273 angle43i ans 06435 The equal toquot relational operator requires both the real and imaginary parts to be equal The other binary relational operators gt lt gt and lt ignore the imaginary part of the number and consider the real part only Operators Expressions use familiar arithmetic operators and precedence rules Addition Subtraction Multiplication Division 2 Matrices and Arrays Left division described in Linear Algebraquot in the MATLAB documentation Power Complex conjugate transpose Specify evaluation order Functions MATLAB provides a large number of standard elementary mathematical functions including abs sq r t exp and sin Taking the square root or logarithm ofa negative number is not an error the appropriate complex result is produced automatically MATLAB also provides many more advanced mathematical functions including Bessel and gamma functions Most of these functions accept complex arguments For a list of the elementary mathematical functions type help elfun For a list of more advanced mathematical and matrix functions type help specfun help elmat Some of the functions like sq r t and sin are built in Builtin functions are part of the MATLAB core so they are very efficient but the computational details are not readily accessible Other functions are implementedin the MATLAB programing language so their computational details are accessible There are some differences between builtin functions and other functions For example for builtin functions you cannot see the code For other functions you can see the code and even modify it if you want Several special functions provide values of useful constants pi 314159265 i Imaginary unit L 1 j Same as i Expressions eps Floatingpoint relative precision E 2 52 39 so realmln Smallest floatingpoint number 2 10 r ealmax 102 Largest floatingpomt number l2 532 a Inf lnfinity NaN Notanumber lnfinity is generated by dividing a nonzero value by zero or by evaluating well defined mathematical expressions that over ow ie exceed r ealmax Notanumber is generated by trying to evaluate expressions like 00 or Inf Inf that do not have well defined mathematical values The function names are not reserved It is possible to overwrite any of them with a new variable such as eps 1e6 and then use that value in subsequent calculations The original function can be restored with clear eps Examples of Expressions You have already seen several examples of MATLAB expressions Here are a few more examples and the resulting values rho 1sqr t52 rho 16180 a abs34i a z sqr tbesselk43r hoi Z 03730 032141 2 Matrices and Arrays huge explogrealmax huge 1 7977e308 toobig pihuge toobig Inf Workinq with Matrices Working with Matrices In this section Generating Matricesquot on page 217 The load Functionquot on page 218 Saving Code to a Filequot on page 218 Concatenation on page 219 Deleting Rows and Columnsquot on page 220 Generating Matrices MATLAB software provides four functions that generate basic matrices z e r o 3 All zeros o n e 3 All ones r and Uniformly distributed random elements r and n Normally distributed random elements Here are some examples Z zer os24 Z O O O O O O O O F 5ones33 F 5 5 5 5 5 5 5 5 5 N fix10r and110 N 9 2 6 4 8 7 4 O 8 4 2 Matrices and Arrays R r andn44 R 06353 00860 03210 12316 06014 20046 12366 10556 05512 04931 06313 01132 10998 04620 23252 03792 The load Function The load function reads binary files containing matrices generated by earlier MATLAB sessions or reads text files containing numeric data The text file should be organized as a rectangular table of numbers separated by blanks with one row per line and an equal number of elements in each row For example outside of MATLAB create a text file containing these four lines 1 1 1 1 Amoco 0010 23232323 0000 0000 0000 3 2 0 1 6 7 15 14 Save the file as mag ik dat in the current directory The statement load magik dat reads the file and creates a variable mag ik containing the example matrix An easy way to read data into MATLAB from many text or binary formats is to use the Import Wizard Saving Code to a File You can create matrices using text files containing MATLAB code Use the MATLAB Editor or another text editor to create a file containing the same statements you would type at the MATLAB command line Save the file under a name that ends in m For example create a file in the current directory named magik m containing these five lines Workinq with Matrices banana oooo mmow oooo bxl LN oooo Amoco 0000 The statement mag ik reads the file and creates a variable A containing the example matrix Concatena on Concatenation is the process ofjoining small matrices to make bigger ones In fact you made your rst matrix by concatenating its individual elements The pair of square brackets is the concatenation operator For an example start with the 4by4 magic square A and form B A A32 A48 A16 The result is an 8by8 matrix obtained by joining the four submatrices B 16 3 2 13 48 35 34 45 5 1O 11 8 37 42 43 4O 9 6 7 12 41 38 39 44 4 15 14 1 36 47 46 33 64 51 5O 61 32 19 18 29 53 58 59 56 21 26 27 24 57 54 55 60 25 22 23 28 52 63 62 49 2O 31 3O 17 This matrix is halfway to being another magic square lts elements are a rearrangement of the integers 1 64 Its column sums are the correct value for an 8by8 magic square sumB ans 260 260 260 260 260 260 260 260 2 Matrices and Arrays But its row sums sum 839 39 are not all the same Further manipulation is necessary to make this a valid 8hy8 magic square Deleting Rows and Columns You can delete rows and columns from a matrix using just a pair of square brackets Start with This changes X to X 16 2 13 5 11 8 9 7 12 4 14 1 If you delete a single element from a matrix the result is not a matrix anymore So expressions like X12 result in an error However using a single subscript deletes a single element or sequence of elements and reshapes the remaining elements into a row vector So X2210 1 results in

### BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.

### You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

## Why people love StudySoup

#### "Knowing I can count on the Elite Notetaker in my class allows me to focus on what the professor is saying instead of just scribbling notes the whole time and falling behind."

#### "When you're taking detailed notes and trying to help everyone else out in the class, it really helps you learn and understand the material...plus I made $280 on my first study guide!"

#### "Knowing I can count on the Elite Notetaker in my class allows me to focus on what the professor is saying instead of just scribbling notes the whole time and falling behind."

#### "Their 'Elite Notetakers' are making over $1,200/month in sales by creating high quality content that helps their classmates in a time of need."

### Refund Policy

#### STUDYSOUP CANCELLATION POLICY

All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email support@studysoup.com

#### STUDYSOUP REFUND POLICY

StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here: support@studysoup.com

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to support@studysoup.com

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.