Introduction to MATLAB

Similar documents
An Introduction to MATLAB

General Information. There are certain MATLAB features you should be aware of before you begin working with MATLAB.

Experiment 1: Introduction to MATLAB I. Introduction. 1.1 Objectives and Expectations: 1.2 What is MATLAB?

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline (Cont d) MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An

Computer Programming ECIV 2303 Chapter 1 Starting with MATLAB Instructor: Dr. Talal Skaik Islamic University of Gaza Faculty of Engineering

Dr Richard Greenaway

MATLAB COURSE FALL 2004 SESSION 1 GETTING STARTED. Christian Daude 1

Outline. CSE 1570 Interacting with MATLAB. Outline. Starting MATLAB. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

CSE/NEUBEH 528 Homework 0: Introduction to Matlab

OUTLINES. Variable names in MATLAB. Matrices, Vectors and Scalar. Entering a vector Colon operator ( : ) Mathematical operations on vectors.

Introduction to Matlab. By: Dr. Maher O. EL-Ghossain

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

EGR 111 Introduction to MATLAB

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

PROGRAMMING WITH MATLAB DR. AHMET AKBULUT

Introduction to MATLAB

Introduction to Engineering gii

Introduction to Octave/Matlab. Deployment of Telecommunication Infrastructures

Variables are used to store data (numbers, letters, etc) in MATLAB. There are a few rules that must be followed when creating variables in MATLAB:

Desktop Command window

Introduction to MATLAB

MATLAB Introduction To Engineering for ECE Topics Covered: 1. Creating Script Files (.m files) 2. Using the Real Time Debugger

Digital Image Analysis and Processing CPE

Matlab Introduction. Scalar Variables and Arithmetic Operators

Creates a 1 X 1 matrix (scalar) with a value of 1 in the column 1, row 1 position and prints the matrix aaa in the command window.

Introduction to MATLAB

AN INTRODUCTION TO MATLAB

Lab of COMP 406. MATLAB: Quick Start. Lab tutor : Gene Yu Zhao Mailbox: or Lab 1: 11th Sep, 2013

PART 1 PROGRAMMING WITH MATHLAB

Our Strategy for Learning Fortran 90

University of Alberta

MATLAB Introduction to MATLAB Programming

McTutorial: A MATLAB Tutorial

Starting with a great calculator... Variables. Comments. Topic 5: Introduction to Programming in Matlab CSSE, UWA

Introduction to MATLAB

Introduction to MATLAB

MATLAB Introductory Course Computer Exercise Session

Chapter 3: Programming with MATLAB

Introduction to MATLAB

MATLAB Project: Getting Started with MATLAB

CITS2401 Computer Analysis & Visualisation

Intermediate Algebra. Gregg Waterman Oregon Institute of Technology

MATLAB Basics. Configure a MATLAB Package 6/7/2017. Stanley Liang, PhD York University. Get a MATLAB Student License on Matworks

General MATLAB Information 1

Constraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial

MATLAB - Lecture # 4

YOGYAKARTA STATE UNIVERSITY MATHEMATICS AND NATURAL SCIENCES FACULTY MATHEMATICS EDUCATION STUDY PROGRAM

Laboratory 1 Octave Tutorial

Introduction to. The Help System. Variable and Memory Management. Matrices Generation. Interactive Calculations. Vectors and Matrices

Matlab for FMRI Module 1: the basics Instructor: Luis Hernandez-Garcia

Starting MATLAB To logon onto a Temple workstation at the Tech Center, follow the directions below.

MATLAB GUIDE UMD PHYS401 SPRING 2012

MATLAB BASICS. Macro II. February 25, T.A.: Lucila Berniell. Macro II (PhD - uc3m) MatLab Basics 02/25/ / 15

MATLAB Lesson I. Chiara Lelli. October 2, Politecnico di Milano

Matlab Tutorial. Get familiar with MATLAB by using tutorials and demos found in MATLAB. You can click Start MATLAB Demos to start the help screen.

Chapter 1 Introduction to MATLAB

A/D Converter. Sampling. Figure 1.1: Block Diagram of a DSP System

MATLAB TUTORIAL WORKSHEET

Step by step set of instructions to accomplish a task or solve a problem

Introduction to Matlab. Summer School CEA-EDF-INRIA 2011 of Numerical Analysis

MATLAB BASICS. M Files. Objectives

1 Introduction to Matlab

1 Overview of the standard Matlab syntax

Computer Programming in MATLAB

MATLAB GUIDE UMD PHYS401 SPRING 2011

MAT 343 Laboratory 1 Matrix and Vector Computations in MATLAB

Starting Matlab. MATLAB Laboratory 09/09/10 Lecture. Command Window. Drives/Directories. Go to.

Dr Richard Greenaway

Variable Definition and Statement Suppression You can create your own variables, and assign them values using = >> a = a = 3.

Introduction to MatLab. Introduction to MatLab K. Craig 1

MATLAB The first steps. Edited by Péter Vass

Getting started with MATLAB

A Guide to Using Some Basic MATLAB Functions

Introduction to Scientific and Engineering Computing, BIL108E. Karaman

What is MATLAB and howtostart it up?

Lecture 1: Hello, MATLAB!

ECE Lesson Plan - Class 1 Fall, 2001

The Very Basics of the R Interpreter

VARIABLES Storing numbers:

MATLAB Project: Getting Started with MATLAB

MATLAB Tutorial. 1. The MATLAB Windows. 2. The Command Windows. 3. Simple scalar or number operations

ANSI C Programming Simple Programs

2.0 MATLAB Fundamentals

Lecturer: Keyvan Dehmamy

An Introduction to MATLAB See Chapter 1 of Gilat

MATLAB BASICS. < Any system: Enter quit at Matlab prompt < PC/Windows: Close command window < To interrupt execution: Enter Ctrl-c.

Getting To Know Matlab

MATLAB Programming for Numerical Computation Dr. Niket Kaisare Department Of Chemical Engineering Indian Institute of Technology, Madras

The Mathematics of Big Data

Appendix A. Introduction to MATLAB. A.1 What Is MATLAB?

Physics 326 Matlab Primer. A Matlab Primer. See the file basics.m, which contains much of the following.

MATH (CRN 13695) Lab 1: Basics for Linear Algebra and Matlab

ECON 502 INTRODUCTION TO MATLAB Nov 9, 2007 TA: Murat Koyuncu

Introduction to Matlab

MATLAB Tutorial. Digital Signal Processing. Course Details. Topics. MATLAB Environment. Introduction. Digital Signal Processing (DSP)

FreeMat Tutorial. 3x + 4y 2z = 5 2x 5y + z = 8 x x + 3y = -1 xx

Programming 1. Script files. help cd Example:

T H E I N T E R A C T I V E S H E L L

Some elements for Matlab programming

Mathworks (company that releases Matlab ) documentation website is:

Transcription:

Introduction to MATLAB 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. current folder Here you enter commands and get results cursor (blinking) command prompt here you can navigate between folders Start Button The MATLAB Start button provides easy access to tools, demos, shortcuts, and documentation. Click the Start button to see the options. 1

Command Window Use the Command Window to enter variables and to run MATLAB functions and scripts. MATLAB displays the results. function result Press the up arrow key to recall a statement you previously typed. Edit the statement as needed, and then press Enter to run it. Command History Statements you enter in the Command Window are logged with a timestamp in the Command History. From the Command History, you can view and search for previously run statements, as well as copy and execute selected statements. You can also create a file from selected statements. 2

Basic Arithmetic 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 power-of-ten scale factor. Imaginary numbers use either i or j as a suffix. Some examples of legal numbers are 3-99 0.0001 9.6397238 1.60210e-20 6.02252e23 1i -3.14159j 3e5i MATLAB stores all numbers internally using the long format specified by the IEEE floating-point standard. Floating-point numbers have a finite precision of roughly 16 significant decimal digits and a finite range of roughly 10-308 to 10 +308. The format Function The format function controls the numeric format of the values displayed. The function affects only how numbers are displayed, not how MATLAB software computes or saves them. Here are the different formats, together with the resulting output produced from a vector x with components of different magnitudes. x = [4/3 1.2345e-6] format short 1.3333 0.0000 format short e 1.3333e+000 1.2345e-006 format short g 1.3333 1.2345e-006 format long 1.33333333333333 0.00000123450000 format long e 1.333333333333333e+000 1.234500000000000e-006 format long g 1.33333333333333 1.2345e-006 format bank 1.33 0.00 format rat 4/3 1/810045 format hex 3ff5555555555555 3eb4b6231abfd271 3

If the largest element of a matrix is larger than 10 3 or smaller than 10-3, MATLAB applies a common scale factor for the short and long formats. In addition to the format functions shown above format compact suppresses many of the blank lines that appear in the output. This lets you view more information on a screen or window. Operators: + Addition Subtraction * Multiplication / Division \ Left division ^ Power ' Transpose + complex conjugate (vectors and matrices) ( ) Specify evaluation order To find a value of a numerical expression, type it in, using the above operators, and hit ENTER. For example to multiply 25.4 and 13.6, type 25.4 * 13.6 at the command prompt and press ENTER. The result looks like this: >> 25.4*13.6 3.4544e+002 The answer is named ans - it is actually a variable or symbolic name that can be called to represent the number should we need it later. Instead we can assign the result to our own variable, which we can name whatever we want, for example x. To do this type: >> x=25.4*13.6 x = 3.4544e+002 Now we might want to multiply the result by something else, say by 1.35, and assign it to another variable, for example y: >>y=x*1.35 y = 4.6634e+002 We still have the value of x. To display it, simply type x and ENTER: >> x x = 3.4544e+002 Suppose we want to try a bunch of operations with two numbers, 2 and 3. We can first assign them to variables a and b: >> a=2 a = 4

2 >> b=3 b = 3 and then do the operations with the values in a, b. >> a*b (multiplication) 6 >> a/b (division) 6.6667e-001 Note that division automatically turned integers to decimals! >> a\b (left division) 1.5000e+000 >> a^b (exponentiation) 8 >> a+b (addition) 5 >> a-b (subtraction) -1 Order of Precedence The precedence followed in mathematical operations in MATLAB is the same as in standard mathematics: exponentiation > multiplication and division > addition and subtraction except that right division takes precedence over left division! To override precedence (or if you re not sure), use parentheses: >> 2*5^2 50 >> (2*5)^2 100 5

The Assignment Operator The equals sign = does not mean equality, it is an assignment operator. It is an instruction to assign a value to a variable. For example, the following produces error: >> x+6=90??? x+6=90 Error: The expression to the left of the equals sign is not a valid target for an assignment. Assignment can be used recursively to increment of change the value of the same variable. >> x=5 x = 5 >> x=2*x+3 x = 13 The value on the right hand side is calculated and assigned to the left hand side. If the value of the right hand side was not defined, the assignment could not be made and we get an error: >> x=5 x = 5 >> x=x+t??? Undefined function or variable 't'. On the other hand: >> x=5 x = 5 >> t=7.5 t = 7.5000e+000 >> x=x+t x = 1.2500e+001 Rules for Naming Variables 1) Only letters, numbers and underscore _ are allowed. 2) No special characters, such as!, @, #, $, %, ^, &, *, <, >, -, +,.,?, {, }, [, ],?. /, \, etc. 3) No spaces 4) Variable name must start with a letter, not number 5) Names are case sensitive 6

Suppressing Output If you simply type a statement and press ENTER, MATLAB automatically displays the results on screen. However, if you end the line with a semicolon, MATLAB performs the computation but does not display any output. This is particularly useful when you generate large matrices. >> x=5; >> y=12; >> z=32; >> (x*y)^2+2*z 3664 with semicolon you can also include multiple statements on the same line: >> x=5;y=12;z=32;(x*y)^2+2*z 3664 Entering Long Statements If a statement does not fit on one line, use an ellipsis (three periods),..., followed by ENTER to indicate that the statement continues on the next line. For example, >> s = 1-1/2 + 1/3-1/4 + 1/5-1/6 + 1/7... - 1/8 + 1/9-1/10 + 1/11-1/12; Blank spaces around the =, +, and - signs are optional, but they improve readability. Command Line Editing Various arrow and control keys on your keyboard allow you to recall, edit, and reuse statements you have typed earlier. For example, suppose you mistakenly enter rho = (1 + sqt(5))/2 You have misspelled sqrt. MATLAB responds with Undefined function or variable 'sqt'. Instead of retyping the entire line, simply press the key. The statement you typed is redisplayed. Use the key to move the cursor over and insert the missing r. Repeated use of the key recalls earlier lines. Typing a few characters and then the key finds a previous line that begins with those characters. You can also copy previously executed statements from the Command History. 7

Characters and Strings Characters and strings (arrays of characters) are created using single quotes: ' '. For example: >>letter = 'A' letter = A >>name = 'string' name = string Clearing Variables Variables in your workspace and their values appear in the Workspace window. To get rid of them use command clear plus what you want to clear. For example: >> clear x y will clear only x and y, but keep the rest. >> clear all will clear the entire workspace, i.e. delete all the variables. The same can be done from the menu, under Edit clicking on Clear Workspace (and confirm). 8

Getting Help MATLAB has extensive documentation and help. Like in any other windows program, you can get help from the menu. If you need help on some specific command, you can type help command in the command window: >> help sqrt SQRT Square root. SQRT(X) is the square root of the elements of X. Complex results are produced if X is not positive. See also sqrtm, realsqrt, hypot. Overloaded methods: codistributed/sqrt Reference page in Help browser doc sqrt Underlined letters are hyperlings, which will take you to help pages for related commands (sqrtm, realsqrt, hypot) or more detailed documentation on sqrt ( doc sqrt ) 9

File Basics There are several ways to save your workspace into file: 1) From the menu: File Save Workspace As. Specify filename (extension.mat) and hit ENTER. It will save the entire workspace. 2) In the command window type: >>save filename.mat again, it will save the entire workspace into the file named filename.mat. If you want to save only specific variables, you need to use a function form of the save command. Functions, as we will learn more in detail later, have arguments in parentheses. In this form the filename can also be a variable. >> filename='test.mat'; >> a=10; >> b=25.5; >> save(filename,'a','b'); Note that all arguments are strings (or characters). To see that a, b really got saved, clear all the variables, load the file and check that a and b have the right values: >> clear all >> load test.mat >> a a = 10 >> b b = 2.5500e+001 >> The load command gets back your saved workspace. Like save, load can also be used with arguments, for example to load only specified variables etc. You can always find more in MATLAB help. Another way to load you workspace is from the menu: File Open and then selecting your.mat file. 10

Often it is useful to save your numbers in a format that you can read or import to other software, in other words in a text file. You can do that using the save command with added argument '-ascii' >> filename='test.prn'; >> a=10; >> b=25.5; >> save(filename,'a','b','-ascii') Now you can open the file test.prn in, for example, Windows Notepad: you can see that both numbers are there, but as real type: a is no longer an integer. You can load the file back: >>load('test.prn') but now any information what was a and what was b is lost. Both numbers are now in a variable (actually an array or vector, because it has two components) called test (the filename used as an argument of the load function test.prn minus the extension.prn). >> test test = 1.0000e+001 2.5500e+001 In general, when you use load command as load('filename.ext') the content will be all in a variable named filename. If there is more than one number, it will be a vector or a matrix. If you want it back to a and b, you need to break it up into its components: >> a=test(1) a = 10 >> b=test(2) b = 2.5500e+001 We will learn how to do manipulations of this kind later when we talk about vectors, arrays and matrices. 11

Writing M files (Scripts) Another important type of a file is M-file, so called because it has extension.m. M-file is a script that MATLAB can read and execute. Another file with extension.m is a function M-file, which we will talk about soon. To write a script, select File New Script. It will open an editor where you can write your script. An example of a script, which reads two numbers from the input and multiplies them is: When you re finished writing your script, save it as myscript.m. It is important that the folder where your script is saved is defined in MATLAB Path! You can add a folder to the Path from the menu: File SetPath, find the folder, click Add Folder and Save. To execute, go to command window and type myscript at the command prompt. It will ask you for a first number (don t forget to hit ENTER after you type it in), then second number. Here is what happens if the second number is zero: >> myscript first number:2 second number:0 cannot divide by zero! and if it is not: >> myscript first number:2 second number:3 6.6667e-001 12

you get the result of dividing the two numbers. 13

There are a lot of things one can learn about MATLAB programming from this simple script: 1) The percent sign % denotes comments, in your MATLAB editor they appear green. Comments are ignored by MATLAB, but are very useful for adding notes, explanations etc. that help read and understand the code. You can put comments wherever you want in your program. In particular the comments right at the top (until the first non-comment line) show up when you call help on your script: >> help myscript myscript.m reads two numbers and divides them You can take advantage of this and put in a simple description of your script. 2) clear all Clears all the variables that might have been assigned at the time you execute your script. It is a good practice for preventing bugs. 3) Function input() R = input('text string') gives the prompt in the text string and then waits for input from the keyboard (until ENTER is pressed). The input have to be numerical (i.e. not character or string) but in general can be any MATLAB expression, which is evaluated, using the variables in the current workspace, and the result returned in R. If the user presses the return key without entering anything, INPUT returns an empty matrix. If you want to input character or string, you have to use R = input('text string','s'), which, again, gives the prompt in the text string and waits for character string input. The typed input is not evaluated; the characters are simply returned as a MATLAB string. 4) if-else-end structure This structure conditionally executes statements. The statement (or statements - there may be more than one) below if (in this case a/b) is executed if the condition right after the if keyword (b~=0, meaning b is not equal zero) is TRUE. Otherwise, the statements under else are executed. The general form is if expression1 statements1 elseif expression2 statements2 else statements3 end The statements1 are executed if the logical expression1 is TRUE, i.e. equal to logical 1. If it is not, the expression 2 at elseif is tested etc. The elseif and else parts are optional. Zero or more elseif parts can be used as well as nested if's. 14

The expressions are usually of the form a rop b where rop is one of the relational operators: == (two equal signs) is equal (TRUE if a and b are equal) < is less (TRUE if a is numerically less than b) > is greater (TRUE if a is numerically greater than b) <= is less or equal (TRUE if a is numerically less or equal to b) >= is greater or equal (TRUE if a is greater or equal to b) ~= is not equal (TRUE if a is not equal to b) More complex logical expressions may include logical operators: For example: && logical AND logical OR ~ logical NOT (as above ~= means NOT equal) if a>b && a>c % if a>b OR c>d disp(' a is greater than b and c ') elseif a>b && a<c disp(' a is greater than b but c is greater than a ') elseif a<b && a>c disp(' a is greater than c but b is greater than a ') else disp(' b and c are both greater than a ') end Be careful with complex logical expressions: relational and logical operators, just like arithmetic operators have different priorities. Use parentheses if not sure. 5) Function disp() disp(a) displays the value of variable a, without printing its name. disp('string') displays string. With these basic commands you will be able to write scripts that can tackle most MATLAB problems. They will include more complex types of variables (arrays, vectors, matrices), functions (MATLAB standard ones and your own) programmed to do specific tasks, you will learn how to create graphs and plots etc., but the actual programming will not get much more difficult than this. 15