A Short Introduction To Matlab: Om Ur U GUR
A Short Introduction To Matlab: Om Ur U GUR
u Omr UGUR
Institute of Applied Mathematics Middle East Technical University, Ankara, Turkey
March 3, 2011
March 3, 2011
1 / 50
Outline
1
Getting Started Introduction Matrices and Vectors Graphics 2-D Plot 3-D Plot Programming in Matlab Introduction Programming Language Vectorisation
March 3, 2011
2 / 50
Getting Started
Introduction
Outline
1
Getting Started Introduction Matrices and Vectors Graphics 2-D Plot 3-D Plot Programming in Matlab Introduction Programming Language Vectorisation
March 3, 2011
3 / 50
Getting Started
Introduction
Calculator
The simplest way to start with Matlab:
>> (-1+2+3)*4 - 5/6, exp(log(2)), sqrt((-2)^3) ans = 15.1667 ans = 2 ans = 0 + 2.8284i
March 3, 2011
4 / 50
Getting Started
Introduction
Variables
Built-in functions and constants:
>> i = cos(pi), eps = 10^(-8), sin = 5 i = 0.2837 eps = 1.0000e-08 sin = 5 >> sin(pi) ??? Index exceeds matrix dimensions. >> clear sin
March 3, 2011
5 / 50
Getting Started
Introduction
Variables (cont.)
Variable names in Matlab must start with a letter and may follow by a combination of letters and numbers: Variable 123 Name is valid.
>> clear all >> myVar = 1 + 2*4, -cos(pi); myVar2 = myVar + ans myVar = 9 myVar2 = 10
March 3, 2011
6 / 50
Getting Started
Introduction
Variables (cont.)
>> who Your variables are: ans >> whos Name ans myVar myVar2 myVar myVar2
Bytes 8 8 8
March 3, 2011
7 / 50
Getting Started
Introduction
Saving
It is possible to save all (or some of) workspace variables to a binary le by typing
>> save myFileName myVars
The option -ascii can be used if binary is not desired. The -append option may be used to add variables to an existing le. Matlab also provides a command diary:
>> diary myDiaryFile.txt >> inDiary = 5 inDiary = 5 >> diary off >> notInDiary = 0; >> diary on >> inDiary = 6; >> diary off
March 3, 2011
8 / 50
Getting Started
Outline
1
Getting Started Introduction Matrices and Vectors Graphics 2-D Plot 3-D Plot Programming in Matlab Introduction Programming Language Vectorisation
March 3, 2011
9 / 50
Getting Started
March 3, 2011
10 / 50
Getting Started
The command rand(state, 13) initialises the uniform random number generator, rand, with the seed that is 13. However, randn generates random numbers that are standard normally distributed. The second line above may be rewritten as follows:
>> b = MT * ( 2*eye(3)*col_v - rand(3,1) ) + 5*ones(3,1);
March 3, 2011
11 / 50
Getting Started
March 3, 2011
12 / 50
Getting Started
March 3, 2011
13 / 50
Getting Started
March 3, 2011
14 / 50
Getting Started
0 0 0
5.0000 0 10.0000
March 3, 2011
15 / 50
Getting Started
Element-wise Computations
Here is an element-by-element operations on matrices:
>> x = linspace(-pi,pi,5), y = x.^2, z = x.*y, y2 = z ./ x x = -3.1416 -1.5708 0 1.5708 3.1416 y = 9.8696 2.4674 0 2.4674 9.8696 z = -31.0063 -3.8758 0 3.8758 31.0063 Warning: Divide by zero. y2 = 9.8696 2.4674 NaN 2.4674 9.8696 >> [1 2; 3 4] .^ [4 3; 2 1] ans = 1 8 9 4
Matlab built-in function linspace(a, b, n): n, is optional and its default value is 100.
March 3, 2011
16 / 50
Getting Started
March 3, 2011
17 / 50
Graphics
2-D Plot
Outline
1
Getting Started Introduction Matrices and Vectors Graphics 2-D Plot 3-D Plot Programming in Matlab Introduction Programming Language Vectorisation
March 3, 2011
18 / 50
Graphics
2-D Plot
Plotting
The most common plotting function in Matlab may be the plot: plot(x, y) or plot(x, y, style)
One can combine several drawings in a single plot function as plot(x1, y1, style1, x2, y2, style2, ...)
March 3, 2011
19 / 50
Graphics
2-D Plot
Plotting (cont.)
>> >> >> >> >> >> x1 = linspace(0,2*pi,20); x2 = 0:pi/20:2*pi; y1 = sin(x1); y2 = cos(x2); y3 = exp(-abs(x1-pi)); plot(x1, y1), hold on plot(x2, y2, r+:), plot(x1, y3, -.o) plot([x1; x1], [y1; y3], -.x), hold off print -depsc -r900 -cmyk ../figures/appendixPlot_1
1
0.8
0.6
0.4
0.2
0.2
0.4
0.6
0.8
Graphics
2-D Plot
Points point circle x-mark plus star square diamond triangle (down) : -. --
March 3, 2011
21 / 50
Graphics
2-D Plot
Plotting: subplot
>> >> >> >> >> >> >> >> >> x = linspace(0,2*pi); subplot(2,2,1); plot(x, sin(x), x, cos(x), --) xlabel(x), ylabel(y), title(Place (1,1)), grid on subplot(2,2,2); plot(exp(i*x)), title(Place (1,2): z = e^{ix}) axis square, text(0,0, i is complex) subplot(2,2,3); polar(x, ones(size(x))), title(Place (2,1)) subplot(2,2,4); semilogx(x,sin(x), x,cos(x), --) title(Place: (2,2)), grid on legend(sin, cos, Location, SouthWest)
Place (1,1) 1 1 Place (1,2): z = eix
0.5
0.5
i is complex
0.5
0.5
1 1
0.5
0.5
Place: (2,2) 1
150
30
0.5
180
330
10
10
Graphics
3-D Plot
Outline
1
Getting Started Introduction Matrices and Vectors Graphics 2-D Plot 3-D Plot Programming in Matlab Introduction Programming Language Vectorisation
March 3, 2011
23 / 50
Graphics
3-D Plot
3-D Plotting
>> x = linspace(-2,2); y = linspace(-2,2,50); >> [X, Y] = meshgrid(x,y); whos Name Size Bytes Class X Y x y 50x100 50x100 1x100 1x50 40000 40000 800 400 double double double double array array array array
Grand total is 10150 elements using 81200 bytes >> X(1:5, 1:5), Y(1:5, ans = -2.0000 -1.9596 -2.0000 -1.9596 -2.0000 -1.9596 -2.0000 -1.9596 -2.0000 -1.9596 ans = -2.0000 -2.0000 -1.9184 -1.9184 -1.8367 -1.8367 -1.7551 -1.7551 -1.6735 -1.6735 1:5) -1.9192 -1.9192 -1.9192 -1.9192 -1.9192 -2.0000 -1.9184 -1.8367 -1.7551 -1.6735 -1.8788 -1.8788 -1.8788 -1.8788 -1.8788 -2.0000 -1.9184 -1.8367 -1.7551 -1.6735 -1.8384 -1.8384 -1.8384 -1.8384 -1.8384 -2.0000 -1.9184 -1.8367 -1.7551 -1.6735
March 3, 2011
24 / 50
Graphics
3-D Plot
Grand total is 5000 elements using 40000 bytes >> >> >> >> >> >> >> >> >> >> subplot(2,2,1), mesh(x,y,z), xlabel(x), ylabel(y) zlabel(z), hold on, contour(x,y,z), title(mesh + contour) subplot(2,2,2), surf(x,y,z), xlabel(x), ylabel(y) zlabel(z), shading interp, title(surf + shading) myZ = z .* exp(-z); subplot(2,2,3), contour3(x,y,myZ,20), xlabel(x), ylabel(y) zlabel(myZ), title(contour3) subplot(2,2,4), H = contour(x,y,myZ); xlabel(x), ylabel(y) zlabel(myZ), title(contour + clabel), clabel(H) print -depsc -r300 -cmyk ../figures/appendixPlot_3D
March 3, 2011
25 / 50
Graphics
3-D Plot
0.05
0.1 0.15 0.2 0.25 0.3 0.35 0.35 0.3 0.25 0.2 0.15 0.1 0.05
0.05
0.05
0.05
Graphics
3-D Plot
March 3, 2011
27 / 50
Graphics
3-D Plot
March 3, 2011
28 / 50
Programming in Matlab
Introduction
Outline
1
Getting Started Introduction Matrices and Vectors Graphics 2-D Plot 3-D Plot Programming in Matlab Introduction Programming Language Vectorisation
March 3, 2011
29 / 50
Programming in Matlab
Introduction
Scripts
Now, suppose that the m-le in Fig. 5 is accessible by Matlab: the le has the name myScript.m and contains just a sequence of Matlab commands and functions.
>> edit myScript.m >> myScript ans = 0.0058 >> who Your variables are: ans myMat n myScript.m % This script computes the determinant of % a randomly chosen square matrix n = 10; % chosen dimension of the square matrix myMat = rand(n); % random matrix det(myMat) % no semi-colon (;) at the end, so displays the output
March 3, 2011
30 / 50
Programming in Matlab
Introduction
Functions
A function in Matlab is dened generally by an m-le that begins with a line of the following form: function outArguments = NameOfFunAsYouLike(inArguments)
myFunction.m function [argOut1, argOut2] = NameOfFunAsYouLike(argIn1, argIn2) % This function computes the determinant of % a randomly chosen square matrix % % argIn1 : dimension of the matrix % argIn2 : seed to the random number generator % argOut1 : the determinant of the matrix % argOut2 : the random matrix % % Usage : [myVar1, myVar2] = myFunction(myInput1, myInput2) rand(state, argIn2); % initialise the rand argOut2 = rand(argIn1); % random matrix argOut1 = det(argOut2); % output depends how you call the function
Programming in Matlab
Introduction
Functions (cont.)
>> clear all >> myFunction(2,13) ans = 0.1341 >> [detA, A] = myFunction(2,13), whos detA = 0.1341 A = 0.8214 0.2119 0.6159 0.3221 Name Size Bytes A ans detA 2x2 1x1 1x1 32 8 8
Grand total is 6 elements using 48 bytes >> detA = myFunction(2,13) detA = 0.1341
March 3, 2011
32 / 50
Programming in Matlab
Introduction
Functions: inline
>> myFun = inline(sin(2*pi*x + theta), x, theta) myFun = Inline function: myFun(x,theta) = sin(2*pi*x + theta) >> myFun(1.5, pi) ans = -4.8986e-16
March 3, 2011
33 / 50
Programming in Matlab
Programming Language
Outline
1
Getting Started Introduction Matrices and Vectors Graphics 2-D Plot 3-D Plot Programming in Matlab Introduction Programming Language Vectorisation
March 3, 2011
34 / 50
Programming in Matlab
Programming Language
General
Matlab provides its programming language that includes looping statements, conditional statements, and relational and logical operators. Moreover, it is also possible to use subroutines or programs, or even, objects written in other programming languages, such as Java, C/C++ or Fortran within Matlab. However, we will restrict ourselves to programming in Matlab and illustrate basic control structures.
March 3, 2011
35 / 50
Programming in Matlab
Programming Language
for loops
The basic syntax is for variable = matrix statements end
myMean.m function myMean = myMean( vector ) % myMean = 0; n = length(vector); for i = 1:n myMean = myMean + vector(i); end myMean = myMean ./ n;
March 3, 2011
36 / 50
Programming in Matlab
Programming Language
March 3, 2011
37 / 50
Programming in Matlab
Programming Language
while loops
Its basic syntax is while expression statements end Some of the logical operators used in Matlab are shown in Table 2.
Table: Some of the logical operators in Matlab
Meaning less than, less than or equal to, etc. equal to, not equal to logical AND logical OR logical NOT
March 3, 2011
38 / 50
Programming in Matlab
Programming Language
The Newtons root nding algorithm approximately computes the solution of the equation f (x) = 0 around a given point x0 : xn+1 = xn f (xn ) , f (xn ) n = 0, 1, 2, . . .
March 3, 2011
39 / 50
Programming in Matlab
Programming Language
Programming in Matlab
Programming Language
if statement
In Matlab, the if statements has the following syntax: if expression1 statements1 elseif expression2 statements2 . . . else statements end
March 3, 2011
41 / 50
Programming in Matlab
Programming Language
if statement (cont.)
myPi.m function myPi = calculatePi(method, nPoints) % calculates approximate value of pi if nargin < 1 myPi = pi; disp([Value of "pi" in Matlab: , num2str(myPi)]); elseif ( nargin < 2 & ~isempty(method) ) disp([You want to calculate "pi" by the method: , num2str(method)]) elseif nargin == 2 myPi = acos(-1); disp([Value of pi = acos(-1): , num2str(myPi)]); else myPi = input(Enter the value of "pi" yourself: ); end
March 3, 2011
42 / 50
Programming in Matlab
Programming Language
if statement (cont.)
>> myPi(); myPi(Monte Carlo); myPi(MC,1e4); Value of "pi" in Matlab: 3.1416 You want to calculate "pi" by the method: Monte Carlo Value of pi = acos(-1): 3.1416 >> myPi(); Enter the value of "pi" yourself: 3 >> myPi([]); Enter the value of "pi" yourself: 3.14 >> myPi([], 10); Value of pi = acos(-1): 3.1416
March 3, 2011
43 / 50
Programming in Matlab
Programming Language
switch statement
The syntax for switch is switch switch expression case case expression1 statements1 case case expression2 statements2 . . . otherwise statements end
March 3, 2011
44 / 50
Programming in Matlab
Programming Language
Programming in Matlab
Vectorisation
Outline
1
Getting Started Introduction Matrices and Vectors Graphics 2-D Plot 3-D Plot Programming in Matlab Introduction Programming Language Vectorisation
March 3, 2011
46 / 50
Programming in Matlab
Vectorisation
March 3, 2011
47 / 50
Programming in Matlab
Vectorisation
Programming in Matlab
Vectorisation
March 3, 2011
49 / 50
Programming in Matlab
Vectorisation
Thanks!...
Thanks!...
March 3, 2011
50 / 50