1 Basic Concepts in Matlab Michael G. Kay Fitts Dept. of Industrial and Systems Engineering North Carolina State University Raleigh, NC 27695-7906, USA kay@ncsu.edu September 2010 Contents 1. The Matlab Environment 1 2. Creating Arrays 1 3. Saving and Loading Variables 2 4. Selecting Array Elements 3 5. Changing and Deleting Array Elements 3 6. Manipulating Arrays 4 7. Multiplication and Addition 4 8. Functions and Scripts 6 9. Anonymous Functions 8 10. Example: Minimum-Distance Location 8 11. Logical Expressions 9 12. Cell Arrays, Structures, and N-D Arrays 9 13. Control Structures 11 14. Example: Random Walk Simulation 13 15. Logical vs. Index Arrays 13 16. Example: The Monti Carlo Method 14 17. Full vs. Sparse Matrices 16 18. Inserting and Extracting Array Elements 16 19. List of Functions Used 16 1. The Matlab Environment After launching Matlab, a multi-panel window appears containing Command Window, Workspace, Current Directory, and Command History panels, among others. This, along with windows for the Editor/Debugger, Array Editor, Help Browser, etc., that can be invoked as needed, is the Matlab environment. Matlab has an extensive set of built-in functions as well as additional toolboxes that consist of functions related to more specialized topics like fuzzy logic, neural networks, signal processing, etc. It can be used in two different ways: as a traditional programming environment and as an interactive calculator. In calculator mode, the built-in and toolbox functions provide a convenient means of performing one-off calculations and graphical plotting; in programming mode, it provides a programming environment (editor, debugger, and profiler) that enables the user to write their own functions and scripts. Expressions consisting of operators and functions that operate on variables are executed at the command-line prompt >> in the Command Window. All of the variables that are created are stored in the workspace and are visible in the Workspace panel. Information about any function or toolbox is available via the command-line help function (or from the doc command that provides the same information in the Help Browser): help sum In Matlab, everything that can be done using the GUI interface (e.g., plotting) can also be accomplished using a command-line equivalent. The command-line equivalent is useful because it can be placed into scripts that can be executed automatically. 2. Creating Arrays The basic data structure in Matlab is the two-dimensional array. Array variables can be scalars, vectors, or matrices: Scalar n = 1 is represented as a 1 1 array Vector a = [1 2 3] is a 1 3 array Matrix 1 2 3 4 5 6 7 8 A is a 2 4 array. Arrays can be created on the command line as follows: n = 1 n = 1 a = [1 2 3] a =