matlab: the basics · 2012. 1. 24. · matlab: the basics dmitry adamskiy [email protected] 9...
TRANSCRIPT
2
Starting Up MATLAB
Windows users: Start up MATLAB by double clicking on the MATLAB icon.
Unix/Linux users: Start up by typing matlab at the operating system prompt.
3
The prompt
Command Window
Command History
Current Directory
Workspace
4
Creating Variables (1)
The names of variables:must begin with a letter but can have
numbers later in the nameare case sensitivecan be up to 32 characters longcannot have spaces or punctuation
marks but underscore “_” is allowedcannot be reserved words like if
5
Creating Variables (2)
To create a variable A with initial value 10, we type:
>> A = 10A = 10A is now stored as a variable in
MATLAB’s memory or workspace with a value 10.
A now can be used in summations, multiplications etc.
6
Manipulating Variables
>> A + Aans = 20We can even assign the results to a new variable:
>> B = A + 5B = 15Or even overwrite a value of a variable
>> A = A * A A = 100
7
List The Variables (1)
>> whos
Name Size Bytes Class
A 1x1 8 double array
B 1x1 8 double array
ans 1x1 8 double array
Grand total is 3 elements using 24 bytes
8
List The Variables (2)
Name : the name you use to refer to the variable
Size: the number of rows (first number) and columns (second number)
Bytes: how much memory the variable uses
Type: all numbers are double arrays by default, but you can also use text, cell and logical
9
Clear Variables
To clear a particular variable A type in:
>> clear A To clear all the variables in the
workspace type in:
>> clear all
10
Suppressing the output
Example:
>> A = 20
A = 20
>> A = 25;
>> A
A = 25
11
MATLAB :Matrices and Punctuation
12
Arrays
Types of arrays: A scalar – a single number
• A = 10
A vector – a row or column of numbers• B = 1 2 3
A matrix – a two-dimensional array• C = 1 5 3 4
5 2 7 8
9 3 4 0
A multi-dimensional array – an array with more than 2 dimensions.
13
Vectors
To enter most data into MATLAB you need to use square brackets [ ]
To specify a row vector RV type in: >> RV = [ 1 2 5 4 ]
or
>> RV = [ 1, 2, 5, 4 ] To specify a column vector CV type in:
>> CV = [ 1 ; 2 ; 5 ; 4 ]
In this context a semi colon means “start a new line”.
14
Matrices (1)
To specify a matrix M of size 2x3 type>> M = [ 1 2 3 ; 4 5 6 ]M = 1 2 3 4 5 6
To refer to the entries in the matrix we use round brackets ()>> M(2,1) ans = 4
o Warning: referring to an index outside the matrix bound will produce an error message.>> M(3,4) ??? Index exceeds matrix dimensions
15
Matrices (2)
You can overwrite the value of an entry in a matrix too.>> M(2,1) = 0M = 1 2 3 0 5 6
You can add a new column/row to the matrix>> M( 3 , : ) = [ 7 8 9 ]M = 1 2 3 0 5 6 7 8 9
Warning: you are only allowed to add a column/row of the same size as the original size of the matrix.
16
The Colon Operator (1)
In round brackets colon means everything in a row or column and is normally used to extract data from a matrix.
M(2,:) means row 2, every column M(:,3) means every row, column 3 M(:) arrange M into a column vector
17
Example
>> M = [1 2 3;4 5 6;7 8 9]M = 1 2 3 4 5 6 7 8 9>> M (2 , :)ans = 4 5 6>> M (: , 3)ans = 3 6 9
18
The Colon Operator (2)
Between the numbers colon means count from A to B one integer at a time
>> D = 5 : 10
D = 5 6 7 8 9 10
>> D(: , 3:5)
ans = 7 8 9
19
The Colon Operator (3)
A set of three numbers separated by colons specifies the step to use for counting.
>> E = 1 : 2 : 10E = 1 3 5 7 9 >> F = 0 : ¼ : 1F = 0 0.25 0.5 0.75 1>> G = 10 : -4 : 2G = 10 6 2
20
Deleting a Row/Column
You can delete rows and columns from a matrix using just a pair of square brackets.
M(:,2)=[] – deletes the second column M(1,:)=[] – deletes the first row M(1,2)=[] – deletion of a single entry from
a matrix results in an error message as the result of this operation is not a matrix anymore.
M(4)=[] – deletes entry number 4 and reshapes the rest into a row vector.
21
Example
>> M = [1 2 3;4 5 6;7 8 9]
M = 1 2 3
4 5 6
7 8 9
>> M(2,:)=[]
M = 1 2 3
7 8 9
>> M(2)=[]
M = 1 2 8 3 9
22
Some special matrices
zeros: all zeros ones: all ones rand: uniformly distributed random
elements randn: normally distributed random
elements
23
Example
>> Z = zeros(2,4)
Z = 0 0 0 0
0 0 0 0
>> F = ones(1,2)
F = 1 1
>> G = 3*ones(2,4)
G = 3 3 3 3
3 3 3 3
24
Example Cont’d
>> R = rand(3 , 2)
R = 0.9501 0.4860
0.2311 0.8913
0.6068 0.7621
>> N = randn(2 , 2)
N = -1.1465 1.1892
1.1909 -0.0376
25
The Array Editor
Click on the “workspace” tab Double click on an array’s name Edit the values you want to change You can copy your data from Excel
and paste them here
26
Exercises
Magic matrix: A square matrix with the property that the sum of its columns, sum of its rows, sum of the elements of its diagonal are all equal.
Type help magic at the prompt to find out more about this.
27
Exercises Cont’d
Clear the workspace by using clear all first and then type the following magic square at prompt. (is there a quicker way of producing this magic square?)
M = 1 6 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
28
Exercises Cont’d
(A) Extract the element at row 2 column 4(B) Extract the entire row 4(C) Extract the entire column 2 (D) Extract columns 1 to 3 at the same time(E) Extract rows 2 and 4 at the same time(F) Update entry of row 2 column 3 to 100(G) Update row 4 to a row of zeros (H) Add a new column of all 1’s to the matrix(I) Add a row of all 9’s to the matrix(J) Delete the entire row 3(K) Multiply all the element of the last row by 5. (hint: use the
end keyword to access the last row)
29
Solutions
Let’s find them together
30
MATLAB :Basic Maths
31
Arithmetic Operators
In MATLAB variables are treated as numbers they represent
Expressions use familiar arithmetic operators and precedence rules
Matrices can be manipulated using operators and pre-defined functions
32
Arithmetic Operators (1)
+ addition
- subtraction
() specify the order of operations
‘ transpose (turn rows into columns and vice versa)
33
Arithmetic Operators (2)
* matrix multiplication/ matrix division.* element-wise multiplication./ element-wise division.^ power
For scalars it does not matter which multiplication or division to use.
34
Example (1)
>> 5 * 4ans = 20>> 6^2ans = 36>> A = 3/4A = 0.7500>> B = A + 5 / 4B = 2
35
Example (2)
>> C = [ 1 2 3 ];>> D = 2*CD = 2 4 6 >> E = [ 2 4 ; 5 6 ; 1 2 ];>> F = D*EF = 30 44>> G = [ 4 2 1];>> H = C.*G H = 4 4 3
36
Example (3)
>> I = [4 5 6; 3 2 4]
I = 4 5 6
3 2 4
>> T = I’
T = 4 3
5 2
6 4
37
Basic Functions
38
What are functions?
Functions are pieces of code written by you or someone else which receive some inputs (arguments) and give you some outputs.
All pre-defined function in MATLAB have a help file to help you use them.
Use help followed by the name of the function for further details.
39
Functions (1)
MATLAB provides a large number of standard elementary mathematical functions, including abs, sqrt, exp and sin.
For a list of these elementary functions type: help elfun
For a list of advanced mathematical and matrix functions, type: help specfun and help elmat
40
Functions (2)
All functions have one or more inputs or arguments and produce one or more outputs.
All functions have the form:
[output1, output2, …] = function (arg1, arg2, …)
Example: M = magic(4);
41
The sum function
S = sum(A) is the sum of the elements of vector A .
S = sum(A,DIM) sums along the dimension DIM.
DIM is the dimension and, for a matrix, can either be 1 (which means columns) or 2 (which indicates rows).
42
The diag Function
diag(A): returns a column vector of the elements of the main diagonal. A has to be a square matrix.
diag(A,n): returns a column vector formed from the elements of the n-th diagonal of the square matrix A.
diag(A,0): is the same as diag(A).
43
Magic Square Example
>> M = magic(4)M = 1 6 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1>> CS = sum(M,1)CS = 34 34 34 34>> US = sum(M)US = 34 34 34 34
44
Example Cont’d
>> RS = sum(M,2)RS = 34
34 34 34
>> first_col = sum(M(:,1))first_col = 34>> second_row = sum(M(2,:))second_row = 34
45
Example Cont’d>> D = diag(M)D = 16
1161
>> SD = sum(D)SD = 34>> SD = sum(diag(M))SD = 34
46
Example Cont’d
>> MM = 1 6 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1>> D_2 = diag(M,2)D_2 = 3
8
47
The size Function
[M,N]= size(A): returns the size of an MxN matrix A in a row vector.
Example:
A = 1 2
3 4
>> size(A)
ans = 2 2
48
The fliplr Function
fliplr(A): returns a new matrix with rows preserved and columns flipped in the left/right direction.
Example:A = 1 2
3 4>> A = fliplr(A)A = 2 1
4 3
49
Example
>> s = size(M)s = 4 4>> M_flipped = fliplr(M)M_flipped =
13 3 2 16 8 10 11 5 12 6 7 9 1 15 14 4
50
Example Cont’d
>> DiagF = diag(M_flipped)DiagF = 13
10 7 4
>> SumF = sum(DaigF)SumF = 34>> SumF = sum(diag(fliplr(M)))SumF = 34
51
Acknowledgements
The material for this handout are taken from MATLAB manuals and http://www.icn.ucl.ac.uk/webspace/users/ahamilton/matlab.htm