INTRODUCTION TO MATLAB
Feb 25, 2016
INTRODUCTION TO MATLAB
Introduction What is Matlab? MATrix LABoratory.
MATLAB is a numerical computing environment and programming language (initially written in C). MATLAB allows easy matrix manipulation, plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs in other languages.
MATLAB makes mathematical operations with vectors y matrices. As a particular case, it can also work with scalar numbers, both reals and complexes.
It has packages with specialized functions.
Basic elements of Matlab’s desktop
Command Windows: Where all commands and programs are run. Write the command or program name and hit Enter.
Command History: Shows the last commands run on the Command Windows. A command can be recovered clicking twice
Current directory: Shows the directory where work will be done.
Workspace: To see the variables in use and their dimensions (if working with matrices)
Help (can also be called from within the comand windows)
Matlab Editor: All Matlab files must end in the .m extension.
CommandWindows
Current directory
CommandHistory
Basic elements of Matlab’s desktop
Matlab editor There can not be empty spaces in the name of the Matlab files
Use “main_” for the name of the main programs, for example: main_curvature
Write “;” at the end of a line If you don’t want that the intermediate calculus is written in the window while the program is running
Write “%” at the beginning of a line to write a comment in the program
Write “…” at the end of a line if you are writing a very long statement and you want to continue in the next line
Matlab editorDebugger
Set/Clear breakingpoint: Sets or clears a break point in the line the cursor is placed.Clear all breakingpoints: Deletes all breaking points.
Step: Executes the current line of the program.
Step in: Executes the current line of the program, if the line calls to a function, steps into the function.
Step out: Returns from a function you stepped in to its calling function without executing the remaining lines individually.Continue: Continues executing code until the next breaking pointQuit debugging: Stops the debugger
Intro MATLAB
Variable Basicsno declarations needed
mixed data types
semi-colon suppresses output of the calculation’s result
>> 16 + 24ans = 40
>> product = 16 * 23.24product = 371.84
>> product = 16 *555.24;>> productproduct = 8883.8
Intro MATLAB
Variable Basics
complex numbers (i or j) require no special handling
clear removes all variables;
clear x y removes only x and y
save/load are used to
retain/restore workspace variables
>> clear>> product = 2 * 3^3;>> comp_sum = (2 + 3i) + (2 - 3i);>> show_i = i^2;>> save three_things>> clear>> load three_things>> whoYour variables are:comp_sum product show_i >> productproduct = 54>> show_ishow_i = -1
use home to clear screen and put cursor at the top of the screen
Numbers and operationsBasic Arithmetic Operations:
Addition: +, Substraction -
Multiplication: *, Division: /
Power: ^
Priority Order: Power, division and multiplication, and lastly addition and substraction. Use () to change the priority.
Example: main_number_operations.m. Try the Debugger
Numbers and operationsMatlab Functions:
exp(x), log(x) (base e), log2(x) (base 2), log10(x) (base 10), sqrt(x)
Trigonometric functions: sin(x), cos(x), tan(x), asin(x), acos(x), atan(x), atan2(x) (entre –pi y pi)
Hyperbolic functions: sinh(x), cosh(x), tanh(x), asinh(x), acosh(x), atanh(x)
Other functions: abs(x) (absolute value), int(x) (integer part ), round(x) (rounds to the closest integer), sign(x) (sign function)
Functions for complex numbers: real(z) (real part), imag(z) (imaginary part), abs(z) (modulus), angle(z) (angle), conj(z) (conjugated)
Example: main_number_operations.m
Vectors and matricesDefining vectors:
Row vectors; elements separated by spaces or comas >> v =[2 3 4]
Column vectors: elements separated by semicolon (;)>> w =[2;3;4;7;9;8]
Length of a vector w: length(w)
Generating row vectors: Specifying the increment h between the elements v=a:h:b Specifying the dimension n: linspace(a,b,n) (by default n=100) Elements logarithmically spaced logspace(a,b,n) (n points
logarithmically spaced between 10a y 10b. By default n=50)
Example: main_matrix_operations.m
Vectors and matricesDefining matrices: It’s not needed to define their size before hand (a size can be
defined and changed afterwards).
Matrices are defined by rows; the elements of one row are separated by spaces or comas. Rows are separated by semicolon (;).
» M=[3 4 5; 6 7 8; 1 -1 0]
Empty matrix: M=[ ];
Information about an element: M(1,3), a row M(2,:), a column M(:,3).
Changing the value of an element: M(2,3)=1;
Deleting a column: M(:,1)=[ ], a row: M(2,:)=[ ];
Example: main_matrix_operations.m
Intro MATLAB
Durer’s Matrix: Creation
» durer1N2row = [16 3 2 13; 5 10 11 8];» durer3row = [9 6 7 12];» durer4row = [4 15 14 1];» durerBy4 = [durer1N2row;durer3row;durer4row];» durerBy4
durerBy4 =
16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1
Intro MATLAB
Easier Way...durerBy4 = 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1
» durerBy4r2 = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]
durerBy4r2 =
16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1
Intro MATLAB
Set FunctionsArrays are ordered sets:
>> a = [1 2 3 4 5]a = 1 2 3 4 5>> b = [3 4 5 6 7]b = 3 4 5 6 7
>> isequal(a,b)ans = 0>> ismember(a,b)ans = 0 0 1 1 1
returns true (1) if arrays are the same size and have the same values
returns 1 where a is in b and 0 otherwise
Intro MATLAB
>> durer = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]
durer = 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1
>> % durer's matrix is "magic" in that all rows, columns,>> % and main diagonals sum to the same number>> column_sum = sum(durer) % MATLAB operates column-wise
column_sum = 34 34 34 34
Matrix OperationsMATLAB also hasmagic(N) (N >
2)function
Intro MATLAB
Dot Operator Example>> A = [1 5 6; 11 9 8; 2 34 78]A = 1 5 6 11 9 8 2 34 78>> B = [16 4 23; 8 123 86; 67 259 5]B = 16 4 23 8 123 86 67 259 5
Vectors and matricesDefining matrices:
Generating de matrices:
Generating a matrix full of zeros, zeros(n,m) Generating a matrix full of ones, ones(n,m) Initializing an identity matrix eye(n,m) Generating a matrix with random elements rand(n,m)
Adding matrices: [X Y] columns, [X; Y] rows
Example: main_matrix_operations.m
Operations with vectors and matricesOperating vectors and matrices with scalars:
v: vector, k: scalar:
v+k addition v-k sustraction v*k product v/k divides each element of v by k k./v divides k by each element of v v.^k powers each element of v to the k-power k.^v powers k to each element of v
Example: main_matrix_operations.m
Operations with vectors and matricesOperating vectors and matrices
+ addition – subtraction * matrix product .* product element by element ^ power .^ power element by element \ left-division / right-division ./ y .\ right and left division element by element Transposed matrix: B=A’ (in complex numbers, it returns the
conjugated transposed, to get only the trasposed: B=A.’)
Example: main_matrix_operations.m
Functions for vectors and matrices sum(v) adds the elements of a vector
prod(v) product of the elements of a vector
dot(v,w) vectors dot product
cross(v,w) cross product
mean(v) (gives the average)
diff(v) (vector whose elements are the differenceof the elements of v)
[y,k]=max(v) maximum value of the elements of a vector (k gives the position), min(v) (minimum value). The maximum value of a matrix M is obtained with max(max(M)) and the minimum with min(min(v))
Some of these operations applied to matrices, give the result by columns.
Functions for vectors and matrices [n,m]=size(M) gives the number of rows and columns
Inverted matrix: B=inv(M), rank: rank(M)
diag(M): gives the diagonal of a matrix. sum(diag(M)) sums the elements of the diagonal of M. diag(M,k) gives the k-th diagonal.
norm(M) norm of a matrix (maximum value of the absolute values of the elements of M)
flipud(M) reorders the matrix, making it symmetrical over an horizontal axis. fliplr(M) ) reorders the matrix, making it symmetrical over a vertical axis.
[V, landa]=eig(M) gives a diagonal matrix landa with the eigenvalues, and another V whose columns are the eigenvectors of M
Example: main_matrix_operations.m
Data input and output
Saving to files and recovering data:
save –mat file_name matrix1_name, matrix2_name
load –mat file_name matrix1_name, matrix2_name
save file_name matrix1_name –ascii (saves 8 figures after the decimal point)
save file_name matrix1_name –ascii –double (saves 16 figures after the decimal point)
Example: main_matrix_operations.m
Matlab Files Program files: Scripts
They are built with a series of commands. The main file will be named main_name.m
Function files
To create your own functions. They are called from within the scripts.
The first line is executable and starts with the word function as showed:
function [output_arg1, output_arg2]=function_name(input_arg1, input_arg2, …, parameters)
The file must be saved as function_name.m
Example: main_plot_sine.m. Use “Step in” in Debugger to enter this function
Intro MATLAB
Vectorization Example*>> type slow.mtic;x=0.1;for k=1:199901 y(k)=besselj(3,x) +
log(x); x=x+0.001;endtoc;>> slowElapsed time is 17.092999 seconds.
*times measured on this laptop
>> type fast.mtic;x=0.1:0.001:200;y=besselj(3,x) + log(x);toc;>> fastElapsed time is 0.551970 seconds.
Roughly 31 times faster without use of for loop
Intro MATLAB
Easy 2-D Graphics>> x = [0: pi/100: pi]; % [start: increment: end]>> y = sin(x);>> plot(x,y), title('Simple Plot')
Intro MATLAB
Adding Another Curve
Line color, style, marker type, all within single quotes; type
>> doc LineSpec
for all available line properties
>> z = cos(x);>> plot(x,y,'g.',x,z,'b-.'),title('More complicated')
Intro MATLAB
You can save and run the file/function/script in one step by clicking here
Tip: semi-colons suppress printing, commas (and semi-colons) allow multiple commands on one line, and 3 dots (…) allow continuation of lines without execution
m-file Editor Window
Intro MATLAB
function [a b c] = myfun(x, y)b = x * y; a = 100; c = x.^2;
>> myfun(2,3) % called with zero outputsans = 100>> u = myfun(2,3) % called with one outputu = 100>> [u v w] = myfun(2,3) % called with all outputsu = 100v = 6w = 4
Functions – First ExampleWrite these two lines to a file myfun.m and save it on MATLAB’s path
Any return value which is not stored in an output variable is simply discarded
ProgrammingLoops
for k=n1:incre:n2
end
for k=vector_column
end
while
end
Example: main_loops
Intro MATLAB
for Loop>> for i = 2:5 for j = 3:6 a(i,j) = (i + j)^2 end end>> aa = 0 0 0 0 0 0 0 0 25 36 49 64 0 0 36 49 64 81 0 0 49 64 81 100 0 0 64 81 100 121
Intro MATLAB
while Loop>> b = 4; a = 2.1; count = 0;>> while b - a > 0.01 a = a + 0.001; count = count + 1; end>> countcount = 1891
ProgrammingConditional control structures
Logical operators: >, <, >=,<=,== (equal) | (or), &(and) ~ (no), ~= (not equal)
Example: main_conditional
ifend
ifelseend
ifelseifelseend
Intro MATLAB
if/elseif/else Statement>> A = 2; B = 3;>> if A > B 'A is bigger' elseif A < B 'B is bigger' elseif A == B 'A equals B' else error('Something odd is happening') endans =B is bigger
ProgrammingStructures of control condicionated: switch
switch is similar to a sequence of if...elseif
Example: main_conditional
switch_expresion=case_expr3 %example
switch switch_expresion
case case_expr1,actions1
case {case_expr2, case_expr3,case_expr4,...}actions2
otherwise, % option by defaultactions3
end
Intro MATLAB
switch Statement>> n = 8n = 8>> switch(rem(n,3)) case 0 m = 'no remainder' case 1 m = ‘the remainder is one' case 2 m = ‘the remainder is two' otherwise error('not possible') endm =the remainder is two