20 views

Uploaded by Mahmoud Basho

- 5564 Quantitative Techniques Sa
- M.B.A.Final Syllabus 2010-2011
- Lec 05 Model Check NAS105
- g.pdf
- Annual XI Comp Sc 2
- DC Motor Driver Circuit
- MATLAB cell arrays intro.pdf
- Flight Direction Cosine Matrix
- Software Environment MATLAB
- Simds
- Dsp Manual 1
- Procesamiento de imagenes
- Tobler 1979 CellularGeog
- Lab 1%2c2%2c3%2c4 Control
- Emanuele Frontoni
- matlab
- Lab1
- JUJ 2008
- Matlab Int
- Matlab Basics

You are on page 1of 21

The purpose of this intro is to show some of Matlabs basic capabilities. Nir Gavish, 2.07

Contents

Getting help Matlab development enviroment Variable denitions Mathematical operations Term by term operations More complicated vector denitions - 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. Matlabs 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 specic command type help sin SIN Sine of argument in radians. SIN(X) is the sine of the elements of X. See also ASIN, SIND.

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 includes a full development enviroment which is composed of Command Window: A line mode interface window for entering Matlab commands and seeing Matlabs 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-les) . To save & run the m-le type F5. To open the editor with a new or old m-le use the command edit mfileName Current Directory: A listing of the les in the current diretory. Doubleclick an m-le to open it in the editor. See this movie for more features of Matlabs development enviroment

http://www.mathworks.com/products/demos/shipping/matlab/WhatsNew_1DevEnviro_viewlet_swf.h

Variable denitions

Matlab variables are dened by assigment. There is no need to declare in advance the variables that we want to use or their type.

% 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 4 7 Name A ans x y z 2 5 8 Size 3x3 1x64 1x1 1x3 3x1 3 6 9 Bytes 72 128 8 24 24 Class double char double double double Attributes

Mathematical operations

The basic mathematical operators of Matlab work with scalar, vector and ma3

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

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 4 7 2 5 8 3 6 9

term_by_term_power_operator = 1 16 49 4 25 64 9 36 81

Clearly, the denition 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 denes a range of values. Notice that for long enough vector it is recommended to suppress the output to the command window by using ; .

% 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

Here are some Matlab operations and functions dened for vectors. Notice that many of these functions can be implemented by a simple loop in our program. It is, however, signicantly faster to use Matlabs 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

Numerically, we cannot represent a general continous function (x,f(x)) because it requires handling innite data (for each point in the range, we need to keep f(x)). Instead, we represent a function by its values at a nite 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 doesnt 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,.);

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])

1 0.8 0.6 0 0.4 0.2 0 0.2 0.4 0.6 0.8 1 0 1 2 3 4 5 6 7 0.05 0.05

3.1

3.2

3.3

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)

a sinus graph 1 0.8 0.6 0.4 0.2 sin(x) 0 0.2 0.4 0.6 0.8 1 0 1 2 3 x 4 5 6

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

sin and cos graph 1 0.8 0.6 0.4 0.2 sin(x) 0 0.2 0.4 0.6 0.8 1 0 1 2 3 x 4 5 6 sin(x) cos(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

40 30 20 10 0

10

5 a sinus graph

10

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 ow 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 = 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 dierent objects: Command window output:

17

In this case, we can only save future output to the command window. The command diary MyCommandWindow saves all output to command window into the .txt le MyCommandWindow until this option is turned o by the command diary off Variables: The following commands save & load the entire workspace into the .mat le MyMatFile save MyMatFile load MyMatFile Graphs The following commands save the current gure % 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;

Tutorials on Matlabs site: http://www.mathworks.com/academia/student_center/tutorials 19

Movie tutorial on Matlabs site http://www.mathworks.com/support/product/demos_index_by_product.html?product=ML Cleves 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, xn = (1)n+1 , 2n 1 n = 1 : 100

Approximate the value of pi using the identity 2 8 1 = 16 (2n 1)2 (2n + 1)2 n=1 Do this by taking the sum of only 100 terms using Matlabs 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 dierent 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 ecient by calculating (n + 1)! = (n + 1)n!

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 rst term of its Taylor series (i.e, sinx=x+...). To distinguish between the graphs, use the line specication r for the Taylor series. Add a plot of the Taylor series with two terms (i.e, sin=x-x3/6+...) and three terms. Use the line specication 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 dened by the following recurrance relation (n + 1)Pn+1 (x) (2n + 1)xPn (x) + nPn1 (x) = 0

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 % Thats it, lets clean up close all;clc;clear all;

21

- 5564 Quantitative Techniques SaUploaded byziabutt
- M.B.A.Final Syllabus 2010-2011Uploaded byshrikantbagal
- Lec 05 Model Check NAS105Uploaded bySrinivas Rallabandi
- g.pdfUploaded byViraj Jain
- Annual XI Comp Sc 2Uploaded byAk Hawk
- DC Motor Driver CircuitUploaded byDharani Raj
- MATLAB cell arrays intro.pdfUploaded byJohn Bofarull Guix
- Flight Direction Cosine MatrixUploaded bysazrad
- Software Environment MATLABUploaded byAvinash Hegde
- SimdsUploaded byfrank
- Dsp Manual 1Uploaded byusama tariq
- Procesamiento de imagenesUploaded byxDragono10
- Tobler 1979 CellularGeogUploaded byJose Northern Lights
- Lab 1%2c2%2c3%2c4 ControlUploaded byKathlyn Yanguez
- Emanuele FrontoniUploaded byDon Vito Andolini
- matlabUploaded byBlack Rabbit
- Lab1Uploaded byRodrigo Samico
- JUJ 2008Uploaded byFatimah Abdul Khalid
- Matlab IntUploaded byHana Hamid
- Matlab BasicsUploaded byAmanda Guimaraes
- intro_matUploaded bybuzz20090
- matlab part1Uploaded byyrikki
- Export Simulation Data - MATLAB & Simulink - MathWorks IndiaUploaded byPasupuleti Sivakumar
- 06 Working from Command Line.pdfUploaded byponpisut
- Lab 3Uploaded bySudipta Dutta
- e9Uploaded byhsanivank
- Lab Assignment on C (MCA)Uploaded byMainak Chakraborty
- ABES Geek-50 Question PaperUploaded byamar7chauhan
- Summer Projects, 17-06-18Uploaded byZiying Fang
- 1992.pdfUploaded byRomano Emmanuelle

- Table of Laplace TransformsUploaded byMahmoud Basho
- DC DRIVRS.pdfUploaded byMahmoud Basho
- Collection of Algebraic FormulaeUploaded byvishnu_mcj
- Basic Electrical EngineeringUploaded byEsse Hist
- Differential Equations Study Guide - ODE SummaryUploaded byMahmoud Basho
- Design With Operational Amplifiers and Analog Integrated Circuits 3E (Sergio Franco)Uploaded bykamran_4507704
- Electrical MachinesUploaded bykranthikoyyada
- Microelectronic Devices_Conduction in SemiconductorsUploaded byMahmoud Basho
- GRIMOIRE OF GEOLOGICAL COMPUTINGUploaded byMahmoud Basho
- Conduction in SemiconductorsUploaded byMahmoud Basho
- ELCE221 Assignment 1 Model AnswerUploaded byMahmoud Basho
- ELCE221 Assignment 2 Model AnswerUploaded byMahmoud Basho
- Panelboard and Switchboards Series Rating Information ManualUploaded byMahmoud Basho
- Discrete Semiconductor Devices and Circuits_40_Signal ModulationUploaded byMahmoud Basho
- Formulae & Tables for use in the State ExaminationsUploaded byMahmoud Basho
- Cutler Hammer - A - Power Distribution System DesignUploaded byogkennyhobo
- Discrete Semiconductor Devices and Circuits_36_Oscillator CircuitsUploaded byMahmoud Basho
- Discrete Semiconductor Devices and Circuits_38_ThyristorsUploaded byMahmoud Basho
- Conversion FormulaeUploaded byavk99
- Table of Logical EquivalencesUploaded byMahmoud Basho
- Discrete Semiconductor Devices and Circuits_41_Power Conversion CircuitsUploaded byMahmoud Basho
- Discrete Semiconductor Devices and Circuits_42_Performance-Based Assessments for Semiconductor Circuit CompetenciesUploaded byMahmoud Basho
- Integral TableUploaded byMahmoud Basho
- Basic Integral TableUploaded bycleous
- Department of Physics - LABORATORY HANDBOOK- 2004-2005Uploaded byMahmoud Basho
- single-page-integral-table.pdfUploaded byMehmet Helva
- Thyristor ApplicationsUploaded byFranz Edvard Bolea Baldazo
- proj_rftUploaded byNoushad Sojib
- Multi Stage Transistero AmplifierUploaded bykaran007_m

- Pure Maths 2013 Specimen Paper Unit 1 Paper 2Uploaded byVanoiMariaStylesWilkinson
- Guide Lines for the Tuning and the Evaluation of Decentralized and Decoupling Controllers for Processes With RecirculationUploaded byRosas Angel
- w16_206_hwk07_solnsUploaded byanthalya
- The Projection Theorem in Hilbert SpacesUploaded byMèo Béo
- igcse maths year 11 revision topics dec 2014Uploaded byapi-241068594
- Second EigenvalueUploaded byMichele Rizzi
- Lid Driven CavityUploaded byali_naghedifar
- Robust and Optimal ControlUploaded byOualid Lamraoui
- Piecewise Silence in Discrete Cosmological Models Timothy Clifton 1 , Daniele Gregoris 2,3,4 , and Kjell Rosquist 2,5 1 School of Physics and Astronomy, Queen Mary University of London, UK. Department of Physics, Stockholm University, 106 91 Stockholm, Sweden. 3 Max-Planck-Institut f ̈ ur Gravitationsphysik (Albert-Einstein-Institut), Am M ̈ uhlenberg 1, 14476 Potsdam, Germany. 4 Erasmus Mundus Joint Doctorate IRAP Ph.D. Student. 5 ICRANet, Piazza della Repubblica, 10, I-65122 Pescara, Italy.Uploaded bymarkrichardmurad
- PHY4460 RelativityUploaded byFranklin Kun Geng
- Numerical Methods Machine Problem 1Uploaded byMaria Charlene Caraos Tapia
- Solucion de EcuacionesUploaded byEraclides Alfaro
- Optimization of the Proportional Navigation Law With Time DelayUploaded bymegustalazorra
- W3INSE6220.pdfUploaded bypicala
- Esfuerzos y Fuerzas en Shell Element Etabs y SapUploaded byluciapfm09
- January 2013 QP - C4 EdexcelUploaded byStylianos_C
- Grad Div Curlin TerpUploaded byStavros Pitelis
- Electronic CompanionUploaded byanonymous author
- Tutorial 3Uploaded byGabriel Mak
- Functions,algebra revision notes from A-level Maths TutorUploaded byA-level Maths Tutor
- Intmath.com-13 tstathe Poisson Probability DistributionUploaded byasif khan
- Sugeno Integral Based On Some InequalitiesUploaded byIOSRjournal
- Ed Tutorials in Operations ResearchUploaded byPasarel Cel Dragutzel
- TS FL TutorialUploaded byHazael Ballesteros Moncada
- 10.1.1.456.1713Uploaded byGustav Chino
- on rational maps with two critical points.psUploaded bySabyasachi Mukherjee
- sequencesUploaded byDorel Barbu
- Non Linear Shooting Algorithm Boundary Value Problem Numerical Analysis Matlab CodeUploaded byshankar
- Chap5.4 HessianUploaded byabarni
- T-DistributionUploaded byapi-19663123