Introduction to Matlab

Similar documents
This is a basic tutorial for the MATLAB program which is a high-performance language for technical computing for platforms:

Introduction to MatLab. Introduction to MatLab K. Craig 1

Introduction to Matlab

A very brief Matlab introduction

Introduction to Matlab

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

To start using Matlab, you only need be concerned with the command window for now.

Introduction to MATLAB

Introduction to Octave/Matlab. Deployment of Telecommunication Infrastructures

Introduction to MATLAB

Introduction to Python Practical 1

MATLAB Basics EE107: COMMUNICATION SYSTEMS HUSSAIN ELKOTBY

PART 1 PROGRAMMING WITH MATHLAB

1 Introduction to Matlab

Introduction to MATLAB LAB 1

AMS 27L LAB #2 Winter 2009

ELEN E3084: Signals and Systems Lab Lab II: Introduction to Matlab (Part II) and Elementary Signals

An Introduction to Numerical Methods

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.

What is MATLAB? What is MATLAB? Programming Environment MATLAB PROGRAMMING. Stands for MATrix LABoratory. A programming environment

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

MATLAB TUTORIAL WORKSHEET

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

An Introduction to MATLAB II

Introduction to MATLAB Practical 1

MATLAB Tutorial EE351M DSP. Created: Thursday Jan 25, 2007 Rayyan Jaber. Modified by: Kitaek Bae. Outline

Matlab Introduction. Scalar Variables and Arithmetic Operators

What is MATLAB? It is a high-level programming language. for numerical computations for symbolic computations for scientific visualizations

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

ARRAY VARIABLES (ROW VECTORS)

MATLAB SUMMARY FOR MATH2070/2970

A Brief Introduction to MATLAB

Introduction to Engineering gii

Introduction to MATLAB

1. Register an account on: using your Oxford address

Matlab Tutorial. The value assigned to a variable can be checked by simply typing in the variable name:

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.

Objectives. 1 Running, and Interface Layout. 2 Toolboxes, Documentation and Tutorials. 3 Basic Calculations. PS 12a Laboratory 1 Spring 2014

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

Welcome to EGR 106 Foundations of Engineering II

MATLAB QUICK START TUTORIAL

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER

STAT/MATH 395 A - PROBABILITY II UW Winter Quarter Matlab Tutorial

Dr Richard Greenaway

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

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

Getting Started with Matlab

ECE 3793 Matlab Project 1

2.0 MATLAB Fundamentals

Laboratory 1 Octave Tutorial

Introduction to Matlab

EEE161 Applied Electromagnetics Laboratory 1

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:

Getting Started. Chapter 1. How to Get Matlab. 1.1 Before We Begin Matlab to Accompany Lay s Linear Algebra Text

EGR 111 Introduction to MATLAB

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

INTRODUCTION TO MATLAB

PC-MATLAB PRIMER. This is intended as a guided tour through PCMATLAB. Type as you go and watch what happens.

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

A Guide to Using Some Basic MATLAB Functions

Introduction to MATLAB Programming

Programming in Mathematics. Mili I. Shah

MATLAB Tutorial. Mohammad Motamed 1. August 28, generates a 3 3 matrix.

MATLAB/Octave Tutorial

PowerPoints organized by Dr. Michael R. Gustafson II, Duke University

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

INTRODUCTION TO MATLAB PLOTTING WITH MATLAB

Introduction to Matlab

PROGRAMMING WITH MATLAB DR. AHMET AKBULUT

Introduction to Matlab

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

Basic Graphs. Dmitry Adamskiy 16 November 2011

Introduction to MATLAB. Computational Probability and Statistics CIS 2033 Section 003

Chapter 2. MATLAB Fundamentals

ELEC4042 Signal Processing 2 MATLAB Review (prepared by A/Prof Ambikairajah)

Matlab Programming Introduction 1 2

12 whereas if I terminate the expression with a semicolon, the printed output is suppressed.

VARIABLES Storing numbers:

MatLab Just a beginning

Introduction to Matlab

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

BEGINNING MATLAB. R.K. Beatson Mathematics Department University of Canterbury. 2 Matlab as a simple matrix calculator 2

Matlab Tutorial 1: Working with variables, arrays, and plotting

Stokes Modelling Workshop

Part V Appendices c Copyright, Todd Young and Martin Mohlenkamp, Department of Mathematics, Ohio University, 2017

Basic MATLAB Intro III

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

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

Introduction to GNU-Octave

LAB 1 General MATLAB Information 1

Lecture 2 Introduction to MATLAB. Dr.Tony Cahill

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

Mathematical Operations with Arrays and Matrices

Eric W. Hansen. The basic data type is a matrix This is the basic paradigm for computation with MATLAB, and the key to its power. Here s an example:

A General Introduction to Matlab

Part #1. A0B17MTB Matlab. Miloslav Čapek Filip Kozák, Viktor Adler, Pavel Valtr

Chapter 1 Introduction to MATLAB

AMS 27L LAB #1 Winter 2009

A very short introduction to Matlab and Octave

Introduction to Matlab

Transcription:

Introduction to Matlab The purpose of this intro is to show some of Matlab s basic capabilities. Nir Gavish, 2.07 Contents Getting help Matlab development enviroment Variable definitions Mathematical operations Term by term operations More complicated vector definitions - the semicolon operator Vector functions and operators Matlab ( continous ) functions Plotting graphs Plotting multiple graphs together Examples of more sophisticated graphics Flow control Saving results Cleaning up More references on the web Exercise 1 Exercise 2 Exercise 3 Exercise 4 Getting help Any intro should start with how to get help. Matlab s documentation is accesable by pressing F1 in Matlab or via the net at http://www.mathworks.com/access/helpdesk/help/techdoc/matlab.html In addition, for specific command type help sin SIN Sine of argument in radians. SIN(X) is the sine of the elements of X. See also ASIN, SIND. 1

Overloaded functions or methods (ones with the same name in other directories) help sym/sin.m Reference page in Help browser doc sin or for a graphical reference of the same help doc sin Matlab development enviroment Matlab includes a full development enviroment which is composed of Command Window: A line mode interface window for entering Matlab commands and seeing Matlab s output. Note, we will usually write Matlab commands in scripts (see editor) and not trough the command window. Workspace: The inventory of all the variables we are using. See http://www.mathworks.com/products/demos/shipping/matlab/workspace.html?product=ml for more details. Also serves an interface to the array editor, see http://www.mathworks.com/products/demos/shipping/matlab/arrayeditor.html?product=ml for more details. Editor: Editor for Matlab scripts (M-files). To save & run the m-file type F5. To open the editor with a new or old m-file use the command edit mfilename Current Directory: A listing of the files in the current diretory. Doubleclick an m-file to open it in the editor. See this movie for more features of Matlab s development enviroment http://www.mathworks.com/products/demos/shipping/matlab/whatsnew_1devenviro_viewlet_swf.h Variable definitions Matlab variables are defined by assigment. There is no need to declare in advance the variables that we want to use or their type. 2

% Define the scalar variable x x=1 % Now a (row) vector y=[1 2 3] % and a column vector z=[1;2;3] % Finally, we define a 3x3 matrix A=[1 2 3;4 5 6;7 8 9] % List of the variables defined whos x = 1 y = 1 2 3 z = 1 2 3 A = 1 2 3 4 5 6 7 8 9 Name Size Bytes Class Attributes A 3x3 72 double ans 1x64 128 char x 1x1 8 double y 1x3 24 double z 3x1 24 double Mathematical operations The basic mathematical operators of Matlab work with scalar, vector and ma- 3

trices. Any combination works, as long as it is mathematically possible. % Adding one to a scalar result1=x+1 % Multiply a vector by a scalar result_x_times_y=x*y % Vector multiplication, same in syntax as any other multiplication result_y_times_z=y*z % Notice that vector multiplication is not commutative result_z_times_y=z*y % More mathematical operators result=(x+1)/2-3*x^2 result1 = 2 result_x_times_y = 1 2 3 result_y_times_z = 14 result_z_times_y = 1 2 3 2 4 6 3 6 9 result = -2 Term by term operations As noted, mathematical operators such as multiplication (*), division (/) or power (ˆ) work between vectors or matrices. In many cases, however, we would 4

like to preform element-wise operations between the two operands. For example, raise to the power of two each term of a matrix, as opposed to multiplying the matrix by itself. This is implemented by term by term operations in Matlab -.*,./,.ˆ. original_matrix=a % Here we use the classical power operator ^ - which multiplies the matrix % by itself classical_power_operator=a^2 % Now we use the term-by-term power operator.^ (notice the dot) - which % multiplies _each term_ of the matrix by itself term_by_term_power_operator=a.^2 original_matrix = 1 2 3 4 5 6 7 8 9 classical_power_operator = 30 36 42 66 81 96 102 126 150 term_by_term_power_operator = 1 4 9 16 25 36 49 64 81 More complicated vector definitions - the semicolon operator Clearly, the definition of vectors by explicitly stating its terms is impractical for vectors with more than a few terms. A better approach is to use the semicolon (:) operator which defines a range of values. Notice that for long enough vector it is recommended to suppress the output to the command window by using ;. 5

% Define vector [1 2 3 4 5] x=1:5 % Define spacing different than one x=1:0.125:5 % Suppress output x=1:0.125:5; x = 1 2 3 4 5 x = Columns 1 through 9 1.0000 1.1250 1.2500 1.3750 1.5000 1.6250 1.7500 1.8750 2.000 Columns 10 through 18 2.1250 2.2500 2.3750 2.5000 2.6250 2.7500 2.8750 3.0000 3.125 Columns 19 through 27 3.2500 3.3750 3.5000 3.6250 3.7500 3.8750 4.0000 4.1250 4.250 Columns 28 through 33 4.3750 4.5000 4.6250 4.7500 4.8750 5.0000 Vector functions and operators Here are some Matlab operations and functions defined for vectors. Notice that many of these functions can be implemented by a simple loop in our program. It is, however, significantly faster to use Matlab s vector function than to use loops in Matlab. The technique of converting a loop in a Matlab program to vector operations is called vectorization and is fundamental in preformance improvement in Matlab. % Transpose of a vector\matrix y_transpose=y % Accessing a specific term of a vector (first term is indexed one, not zero) y2=y(2) 6

% A partial list of vector functions % sum(y) = sum all the values of the vector y res_sum = sum(y) % prod(y) = multiply all the values of the vector y res_prod = prod(y) % diff(y) = [y(2)-y(1),y(3)-y(2),..., y(n)-y(n-1)] res_diff = diff(y) y_transpose = 1 2 3 y2 = 2 res_sum = 6 res_prod = 6 res_diff = 1 1 Matlab ( continous ) functions Numerically, we cannot represent a general continous function (x,f(x)) because it requires handling infinite data (for each point in the range, we need to keep f(x)). Instead, we represent a function by its values at a finite number of data points (x i,f(x i)), where the series of points {x i} is typically referred to as the sampling points or the grid points. Accordingly, the continous functions in Matlab accepts a vector of point {x i} and return a vector of values {f(x i)}. We note that opposed to the numerical approach is the symbolic approach, which is the approach you know from all the basic math classes. 7

% define the grid {1,1.1,1.2...4.9,5} using the semicolon operator x=1:0.1:5; % f(x) = x^2/(4+x), notice the use of *term-by-term operators* f1 = x.^2./(4+x); % sqrt(x) = x^(1/2) f2 = sqrt(x + x.^3); % Note: MATLAB doesn t define the constant e. Use exp(1) to get e. f3 = exp(x); % Note: in MATLAB log() means ln() (i.e., log in base e). f4 = log(x+4); % pi is a matlab constant. Note: sin, cos, etc. are in radians (NOT in degrees!) f5 = cos(pi)*tan(x); % abs(x) := x f6 = abs(f5); % sign(x) gives -1 for x<0, 0 for x=0, and +1 for x>0 f7 = sign(f5); Plotting graphs Matlab is well-known for its plotting capabilites and for their simplicity of use. We now go over the most basic plot command and its features - plot(x,y) which plots the data points {x i,f(x i)} % Define the grid and the "continous" function sin x=0:0.01:2*pi; y=sin(x); % Plot the points (x,sin(x)) plot(x,y,. ); 8

1 0.8 0.6 0.4 0.2 0 0.2 0.4 0.6 0.8 1 0 1 2 3 4 5 6 7 As you see, the plot command displays a graph of (x,sin(x)) which looks continous. However, a closer look at the data shows it is not really continous. You can ignore the commands used to demonstrate it. plot(x,y,. ); annotation( rectangle,[0.4518 0.4976 0.04643 0.05]); axes( Position,[0.5554 0.5929 0.3232 0.2714]); plot(x,y,. );axis([2.94 3.33-0.05 0.05]) 9

1 0.8 0.05 0.6 0.4 0.2 0 0.2 0.4 0 0.05 3 3.1 3.2 3.3 0.6 0.8 1 0 1 2 3 4 5 6 7 The default command connects every two points, making the graph look continous. % Close the last graph to clean up the prior setting of double axes close all; % Plot using the default option plot(x,y); 1 0.8 0.6 0.4 0.2 0 0.2 0.4 0.6 0.8 1 0 1 2 3 4 5 6 7 10

The last graph is ugly and not very informative. Let us now improve its look plot(x,y); % Set the axis boundaries. Note: The data should not touch the axis, % therefore the y axis is set to be -1.05 to 1.05. axis([0 2*pi -1.05 1.05]) % Add a label for the x-axis xlabel( x ); % Add a label for the y-axis ylabel( sin(x) ); % Add a title for the y-axis title( a sinus graph ) 1 a sinus graph 0.8 0.6 0.4 0.2 sin(x) 0 0.2 0.4 0.6 0.8 1 0 1 2 3 4 5 6 x Plotting multiple graphs together Often we need to plot more than one function, for example - to compare the output of two processes or get an easy look at various measures at once. There are two ways to plot multiple functions Adding graphs to an existing axes, so that in the same axes you get multiple plots. This is done by the hold command. Adding a new axes are plotting the graph there. This is done by the subplot command. 11

% add the cos graph to the exisiting plot % tell Matlab to hold the graph for the next plot hold % plot the additional graph, the additional parameter r is for red plot(x,cos(x), r ); % add a legend for the two plots legend( sin(x), cos(x) ) % correct the title title( sin and cos graph ) Current plot held 1 0.8 0.6 0.4 0.2 sin and cos graph sin(x) cos(x) sin(x) 0 0.2 0.4 0.6 0.8 1 0 1 2 3 4 5 6 x We now split the page into several axes by the subplot command Its syntax is subplot(row num,col num,curr plot) % split the screen into 2 rows and 3 columns of axes, set the next plot to be at % the first axes subplot(2,3,1); % plot a graph of x plot(x,x); % Now go to the second axes subplot(2,3,2); % plot a graph of x^2 plot(x,x.^2); % Next, plot a graph of sin in the fifth axes. Notice, all editing of the 12

% graph applies only to the current axes subplot(2,3,5); % plot a graph of sin(x) plot(x,y); % set axis axis([0 2*pi -1.05 1.05]) % Add a label for the x-axis xlabel( x ); % Add a label for the y-axis ylabel( sin(x) ); % Add a title title( a sinus graph ) 13

8 6 4 2 0 0 5 10 40 30 20 10 0 0 5 10 1 a sinus graph 0.5 sin(x) 0 0.5 1 0 5 x Examples of more sophisticated graphics The number of line codes needed to produces these graphs is no more than 10-20 lines. cruller; logo;figure; spharm2; 14

15

Flow control Here I just give examples for the most basic flow control commands. For more info see http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/ Conditional control a=4; if a==5 a=a+1 else a=3 end 16

a = 3 Loop Control for ix=1:3 a=a+ix end a = 4 a = 6 a = 9 Notice that I name the enumerator index ix and not i or j. This is because i and j are the complex imaginary numbers, e.g., i_square=i^2 i_square = -1 Saving results We can save all our results for future reference. Here we discuss three different objects: Command window output: 17

In this case, we can only save future output to the command window. command The diary MyCommandWindow saves all output to command window into the.txt file MyCommandWindow until this option is turned off by the command diary off Variables: The following commands save & load the entire workspace into the.mat file MyMatFile save MyMatFile load MyMatFile Graphs The following commands save the current figure % save as jpeg (not optimal for graphs, good compression) print -djpeg mypic.jpeg % save as tiff (much better for graphs, more space) print -dtiff mypic.tif 18

Cleaning up Since memory is not erased at the begging and end of a script, it is a good habit to clean up before and after the script run. % Close all plot windows close all; % Erase the command window (You can still see the last command in the command history w clc; % Clear all variables from the workspace. clear all; More references on the web Tutorials on Matlab s site: http://www.mathworks.com/academia/student_center/tutorials 19

Movie tutorial on Matlab s site http://www.mathworks.com/support/product/demos_index_by_product.html?product=ml Cleve s Moler (free online) book http://www.mathworks.com/moler/chapters.html Exercise 1 Create a vector of the even whole numbers between 31 and 75. Create a vector x with the elements, x n = ( 1)n+1 2n 1, n = 1 : 100 Approximate the value of pi using the identity π 2 8 16 = n=1 1 (2n 1) 2 (2n + 1) 2 Do this by taking the sum of only 100 terms using Matlab s sum command. Use the Matlab constant pi to calcuate the accuracy of your calculation. Let A=[8 1 6;3 5 7;4 9 2]. Calcuate the sum over the rows of A by multiplication of A by a appropriate vector. Let A=[8 1 6;3 5 7;4 9 2]. Calcuate the sum over the rows of A by using the command sum. Exercise 2 In this exercise you will write a program that calculates the factorials 1!, 2!, 3!... 15! in three different ways Look for help on the command factorial and write a program that calculates 1!, 2!, 3!... 15! Write a program that calculates 1!, 2!, 3!... 15! without using factorial. Make the program efficient by calculating (n + 1)! = (n + 1)n! Vectorize the code by using the command cumprod (look it up...). 20

Exercise 3 In this exercise you produce a graphical example of the accuary of a Taylor series Plot sin(x) in the domain [0,pi] Add a plot of the first term of its Taylor series (i.e, sinx=x+...). To distinguish between the graphs, use the line specification r for the Taylor series. Add a plot of the Taylor series with two terms (i.e, sin=x-xˆ3/6+...) and three terms. Use the line specification g: and k.-, respectively. Make the graph readable by adding axis labels, adding a legend and setting the axis. Exercise 4 The Legendre polynomials (Pn(x)) are defined by the following recurrance relation (n + 1)P n+1 (x) (2n + 1)xP n (x) + np n 1 (x) = 0 with P 1 (x) = x, P 0 (x) = 1 Compute the next three Legendre polynomials by implementing the recursive relation in Matlab and using vectorial operations only for x=-1:0.01:1. Plot all 5 over the interval [-1,1] (use x=-1:0.01:1). Make sure the graph is well presented % That s it, let s clean up close all;clc;clear all; 21