









Prepara tus exámenes y mejora tus resultados gracias a la gran cantidad de recursos disponibles en Docsity
Gana puntos ayudando a otros estudiantes o consíguelos activando un Plan Premium
Esta página no es visible en la vista previa
¡No te pierdas las partes importantes!










After launching Matlab (requires, at least, version 2016b), a multi-panel window appears containing Command Window, Workspace, Current Directory, and Command History panels, among others. This, along with windows for the Editor/Debugger, Array Editor, Help Browser, etc., that can be invoked as needed, is the Matlab environment. Matlab has an extensive set of built-in functions as well as additional toolboxes that consist of functions related to more specialized topics like fuzzy logic, neural networks, signal processing, etc. It can be used in two different ways: as a traditional programming environment and as an interactive calculator. In calculator mode , the built-in and toolbox functions provide a convenient means of performing one-off calculations and graphical plotting; in programming mode , it provides a programming environment (editor, debugger, and
profiler) that enables the user to write their own functions and scripts. Expressions consisting of operators and functions that operate on variables are executed at the command-line prompt >> in the Command Window. All of the variables that are created are stored in the workspace and are visible in the Workspace panel. Information about any function or toolbox is available via the command-line help function (or from the doc command that provides the same information in the Help Browser): help sum In Matlab, everything that can be done using the GUI interface (e.g., plotting) can also be accomplished using a command-line equivalent. The command-line equivalent is useful because it can be placed into scripts that can be executed automatically.
The basic data structure in Matlab is the two-dimensional array. Array variables can be scalars, vectors, or matrices: Scalar n = 1 is represented as a 1 1 array Vector a = [1 2 3] is a 1 3 array
Matrix ^
A (^) 5 6 7 8 is a 2 4 array.
Arrays can be created on the command line as follows: n = 1 n = 1 a = [1 2 3] a = 1 2 3
S AVING AND L OADING V ARIABLES
In Matlab, the case of a variable matters; e.g., the arrays a and A are different variables. To recall the last command executed, press the up-arrow key (). To suppress the output from a command, end an expression with a semicolon (;): A = [1 2 3 4; 5 6 7 8];
An empty array is considered a 0 0 matrix: a = [] a = [] The following operators and functions can be used to automatically create basic structured arrays: a = 1: a = 1 2 3 4 5 a = 1:2: a = 1 3 5 a = 10:-2: a = 10 8 6 4 2 a = ones(1,5) a = 1 1 1 1 1 a = ones(5,1) a = 1 1 1 1 1 a = zeros(1,5) a = 0 0 0 0 0
The rand function generates random numbers between 0 and 1. (Each time it is run, it generates different numbers.) a = rand(1,3) a = 0.6086 0.2497 0. b = rand(1,3) b = 0.2618 0.4760 0. A random permutation of the integers 1 to n can be generates using the randperm(n) function: randperm(5) ans = 1 3 4 5 2 To create a 3 3 identity matrix: eye(3) ans = 1 0 0 0 1 0 0 0 1 The variable ans is used as a default name for any expression that is not assigned to a variable.
The variables currently in the workspace are visible in the Workspace panel, or through the whos command: whos Name Size Bytes Class Attributes A 2x4 64 double a 1x3 24 double ans 3x3 72 double b 1x3 24 double n 1x1 8 double To save arrays A and a to a file: save myvar A a Data files in Matlab have the extension .mat, so the file myvar.mat would be saved in the current directory (see Current Directory panel). To remove the variables from the workspace: clear whos To restore the variables:
M ANIPULATING A RRAYS
To delete selected elements of a vector: a(3) = [] a = 7 6 4 5 a([1 4]) = [] a = 6 4 A row or column of a matrix can be deleted by assigning it to an empty array: A(:,2) = [] A = 1 3 4 5 7 8
The following operators and functions can be used to manipulate arrays: A A = 1 3 4 5 7 8 A' (Transpose) ans = 1 5 3 7 4 8 fliplr(A) (Flip left/right) ans = 4 3 1 8 7 5 flipud(A) (Flip up/down) ans = 5 7 8 1 3 4 [A B] (Concatenate matrices) ans = 1 3 4 3 4
ans = 1 3 4 10 5 7 8 20 30 40 50 60 A(:) (Convert matrix to column vector) ans = 1 5 3 7 4 8
A = A(:)' (Convert matrix to row vector) A = 1 5 3 7 4 8 A = reshape(A,2,3) (Convert back to matrix) A = 1 3 4 5 7 8
A scalar can be added to or multiplied with each element of an array; e.g., A A = 1 3 4 5 7 8 2 + A ans = 3 5 6 7 9 10 B = 2 * A B = 2 6 8
M ULTIPLICATION AND A DDITION
Arrays are multiplied together in two different ways: matrix multiplication, where the inner dimensions of the arrays must be the same, and element-by-element multiplication, indicated by the use of a dot (.) along with the operator, where the arrays must have compatible sizes : two arrays have compatible sizes if each respective dimension either (a) has the same size, or (b) the size of one of the arrays is one, in which case the array with the size-one dimension is automatically duplicated so that it matches the size of the other array, resulting in an output array with a dimension is equal to the non-one size dimension; i.e.,
Matrix multiplication : A (^) m n B n (^) p C m p
A * B (Error: 2 3 * 2 3 ≠ 2 3) Error using __ Inner matrix dimensions must agree.*
C = A * B' (2 3 * 3 2 = 22) C = 52 116 116 276
C = A' * B (3 2 * 2 3 = 33) C = 52 76 88 76 116 136 88 136 160 a = 1: a = 1 2 3
a * a' (1 3 * 3 1 = 11) ans =
A * a' (2 3 * 3 1 = 21) ans = 19 43 Division (./) and power (.^) operators can also be preformed element by element.
Arrays are added together in Matlab element by element; thus, each array must be the same size or compatible size; i.e., Addition : A (^) m n B m n (^) C m n A (^) m n b 1 (^) n C m n a m (^) 1 B m n (^) C m n a m (^) 1 b 1 (^) n C m n a 1 (^) n b m (^) 1 C m n C = A + B (2 3. * 2 3 = 23) C = 3 9 12 15 21 24 To add (row) vector a to each row of A : a + A (1 3 + 2 3 = 23) ans = 2 5 7 6 9 11 The size of column vector b is not compatible with A : b = [4:6]’ b = 4 5 6 b + A (Error: 3 1 + 2 3 ≠ 2 3) Matrix dimensions must agree. Convert b to a row vector so that it has a compatible size with A : b(:)’ + A (1 3 + 2 3 = 23) ans = 5 8 10 9 12 14
FUNCTIONS AND S CRIPTS
The first step is to subtract x from each row in P : x - P ans = 2 0 -3 0 -3 - Square each element of the result: (x - P) .^ 2 ans = 4 0 9 0 9 16 Add the elements in each row: sum((x - P).^2, 2) ans = 4 9 25 Then take the square root and assign the result to d : d = sqrt(sum((x - P).^2,2)) d = 2 3 5 The M-File Editor can be used to create the text file for the function mydist. Either select New, M-File from the File menu, or edit mydist
where the editor should appear. Type the following two lines (adding a semicolon to the end of the command-line expression to suppress output from inside the function): function d = mydist(x,P) d = sqrt(sum((x - P).^2,2)); Save the file, then check to see if Matlab can find the file by using the type command to print the function at the command line, and then check to see that it works as desired: type mydist function d = mydist(x,P) d = sqrt(sum((x - P).^2,2)); d = mydist(x,P) d = 2 3 5 As it is written, the function will work for points of any dimension, not just 2-D points. For n -dimensional points, x would be a n -element vector and P a m n matrix; e.g., for 4- D points: d = mydist([x x],[P P]) d =
The only thing “hard-coded” in the function is that x has to be input as an n -element row vector to be compatible. In case x is input as a column vector, x(:)’ can be used to force x to be a row vector. Although the length and size functions could be used to determine if the number of elements in x equals the number of columns (dimension 2) in P , if they are not compatible, Matlab will automatically catch the error (you need only add code in you function to check for errors not otherwise caught), n = length(x) n = 2 size(P,2) ans = 2 The last thing that should be added to the function is some help information. All of the first block of contiguous comment lines in a function is returned when the help
1 3 6
1
5
2 3
5
1 2
3
x
A NONYMOUS FUNCTIONS
command is executed for the function. Comment lines are indicated by an asterisk (%).
To get help: help mydist MYDIST Euclidean distance from x to P. d = mydist(x,P) x = n-element vector single point P = m x n matrix of n points d = m-element vector, where d(i) = distance from x to P(i,:) The function mydist can now be used inside of any expression; e.g., sumd = sum(mydist(x,P)) sumd = 10
Anonymous functions provide a means of creating simple functions without having to create M-files. Given x = [3 1]; P = [1 1; 6 1; 6 5]; the sum of the distances from x to each of the points in P can be determined by creating a function handle sumMydist to an anonymous function: sumMydist = @() sum(mydist(x,P)); sumMydist sumMydist = function_handle with value: @()sum(mydist(x,P)) sumMydist() ans =
The values of x and P are fixed at the time sumMydist is created. To make it possible to use different values for x : sumMydist = @(x) sum(mydist(x,P)); sumMydist([6 1]) ans = 9 sumMydist([4 3]) ans =
Anonymous functions can be used as input arguments to other functions. For example, fminsearch performs general- purpose minimization. Starting from an initial location x 0 , it can be used to determine the location x that minimizes the sum of distances to each point in P : x0 = [0 0]; [x,sumd] = fminsearch(sumMydist,x0) x = 5.0895 1. sumd =
For this particular location problem, any initial location can be used to find the optimal location because the objective is convex: [x,sumd] = fminsearch(sumMydist,[ 5]) x = 5.0895 1. sumd =
For many (non-convex) problems, different initial starting values will result in different (locally optimal) solutions.
A logical array of 1 (true) and 0 (false) values is returned as a result of applying logical operators to arrays; e.g., a = [4 0 -2 7 0] a = 4 0 -2 7 0
CELL A RRAYS, S TRUCTURES , AND N-D A RRAYS
t = {'Miami','Detroit','Boston'} t = 1×3 cell array 'Miami' 'Detroit' 'Boston' Some functions can accept a cell array as input: t = sort(t) t = 1×3 cell array 'Boston' 'Detroit' 'Miami' A cell array can be used to store any type of data, including other cell arrays. One use of a cell array is to store all of the input arguments for a function: xP = {x, P} xP = [1x2 double] [3x2 double] The arguments can then be passed to a function by generating a comma-separated list from the cell array: d = mydist(xP{:}) d =
Cell arrays can be created using the cell function: c = cell(1,3) c = 1×3 cell array [] [] [] Non-empty values can then be assigned to each element using a FOR Loop (see Section 13 below). A cell array can be both created and assigned non-empty values by using the deal function: [c2{1:3}] = deal(0) c2 = 1×3 cell array [0] [0] [0] [c3{1:3}] = deal(1,2,3) c3 = 1×3 cell array [1] [2] [3]
Structures are used to group together related information. Each element of a structure is a field : s.Name = 'Mike' s = struct with fields: Name: 'Mike' s.Age = 44 s = struct with fields: Name: 'Mike' Age: 44 Structures can be combines into structure arrays: s(2).Name = 'Bill' s = 1x2 struct array with fields: Name Age s(2).Age = 40; s(2) ans = struct with fields: Name: 'Bill' Age: 40 s.Name ans = Mike ans = Bill An alternate way to construct a structure array is to use the struct function: s = struct('Name',{'Mike','Bill'},'Age',{44,40}) s = 1x2 struct array with fields: Name Age When needed, the elements in each field in the array can be assigned to separate arrays:
CONTROL S TRUCTURES
names = {s.Name} names = 1×2 cell array 'Mike' 'Bill' ages = [s.Age] ages = 44 40 An alternate way to do the same thing that is sometimes more efficient is to use a single structure instead of an array of structures and use an array for each field of the structure: s2.Name = {'Mike','Bill'} s2 = struct with fields: Name: {'Mike' 'Bill'} s2.Age = [44 40] s2 = struct with fields: Name: {'Mike' 'Bill'} Age: [44 40]
Multidimensional, or N-D, arrays extend the basic 2-D array used in Matlab. N-D arrays cannot be stored as sparse arrays, so they should only be used for dense arrays. N-D array can be created by extending a 2-D array or by directly creating the array using functions like zeros and ones: D3 = [1 2 3; 4 5 6] D3 = 1 2 3 4 5 6 D3(:,:,2) = [7 8 9; 10 11 12] D3(:,:,1) = 1 2 3 4 5 6 D3(:,:,2) = 7 8 9 10 11 12 To access individual elements and cross-sections: D3(1,3,2) ans =
ans(:,:,1) = 1 4 ans(:,:,2) = 7 10 To convert the 3-D answer to a 2-D array: D2 = squeeze(D3(:,1,:)) D2 = 1 7 4 10
In Matlab, FOR loops iterate over the columns of an array, and logical expressions are used for conditional evaluation in IF statements and WHILE loops.
for i = 1: i end i = 1 i = 2 i = 3 for i = 5:-2:1, i, end i = 5 i = 3 i = 1 Any type of array can be used; e.g., a character array : chararray = 'abc'
EXAMPLE : R ANDOM W ALK S IMULATION
a = [5 0 -1 9 0]; a > 0 ans = 1×5 logical array 1 0 0 1 0 any(a > 0) ans = logical 1 all(a > 0) ans = logical 0
The following example simulates a random walk. Starting from the origin at 0, there is a 50–50 chance that the next step is up one unit of distance (+1) or down one unit of distance (–1). The vector d represents the cumulative distance from the origin at each step: Start by using only 5 steps (and, to get the same random numbers as show below, the state of the random number generator can first be set to some arbitrary number like 123). rng(123) s = rand(1,5) s = 0.6965 0.2861 0. 0.5513 0. s > 0. ans = 1×5 logical array 1 0 0 1 1 (s > 0.5)* ans = 2 0 0 2 2 ((s > 0.5)2) - 1* ans = 1 -1 -1 1 1 d = cumsum(((s > 0.5)2) - 1)* d =
Now increase to 100 steps (and use semicolon so output is suppressed): s = rand(1,100); d = cumsum(((s > 0.5)2) - 1); plot(d)*
Multiple runs of the simulation can be used to verify the theoretical estimate of the expected distance from the origin after t steps, where d ( t ) is the last element of d :
E d t ( ) 2 t
A FOR-loop can be used iterate through 100 runs of a 1, step random walk: for i = 1: d = cumsum(((rand(1,1000)>0.5)2)-1); dt(i) = d(end); end mean(abs(dt))* (Sample mean) ans =
This compares with the theoretical estimate:
Logical arrays and index arrays provide alternative means of selecting and changing the elements of an array. The find function converts a logical array into an index array: a
-8 0 10 20 30 40 50 60 70 80 90 100
0
2
4
6
EXAMPLE : THE M ONTI CARLO M ETHOD
a = 5 0 -1 9 0 ispos = a > 0 (Logical array) ispos = 1×5 logical array 1 0 0 1 0 a(ispos) ans = 5 9 idxpos = find(a > 0) (Index array) idxpos = 1 4 a(idxpos) ans = 5 9 Some functions return logical or index arrays: s = {'Miami','Detroit','Boston'}; idxDetroit = strmatch('Detroit',s) idxDetroit = 2 isDetroit = strcmpi('detroit',s) isDetroit = 1×3 logical array 0 1 0 Although similar, the use of logical and index arrays have different advantages:
The Monti Carlo method is a general-purpose simulation technique that uses random numbers to estimate the solutions to problems that are too difficult to solve analytically or by using other, more specialized, approximation techniques. It differs from other types of simulation because it is used for static problems where time is not involved.
FULL VS. S PARSE M ATRICES
In many applications, only a small number of the elements of a matrix will have nonzero values. For efficiency, these matrices can be stored as sparse matrices instead of as normal full matrices; e.g., A = [0 0 0 30; 10 0 20 0] A = 0 0 0 30 10 0 20 0 sparse(A) ans = (2,1) 10 (2,3) 20 (1,4) 30 full(A) ans = 0 0 0 30 10 0 20 0
The sparse function can be used to create a 2 3 matrix A with nonzero values A (1,4) = 30, A (2,1) = 10, and A (2,3) = 20: A = sparse([1 2 2], [4 1 3], [30 10 20], 2, 4) A = (2,1) 10 (2,3) 20 (1,4) 30
If a 2 3 matrix B exists, new values can be inserted into B by first creating a sparse matrix with the same size as B with nonzero values corresponding to the elements to be inserted in B ; e.g., to insert the nonzero values of A into B : B = [1:4; 5:8] B = 1 2 3 4 5 6 7 8 B(A ~= 0) = A(A ~= 0) B = 1 2 3 30 10 6 20 8
The (1,4), (2,1), and (2,3) elements of B can be extracted to the vector b as follows: B([1 2 2],[4 1 3]) ans = 30 1 3 8 10 20 8 10 20 b = diag(B([1 2 2],[4 1 3])) b = 30 10 20
abs help sort clear length sparse cumsum load sqrt deal mean squeeze diag min strcmpi disp ones strmatch doc plot struct eye rand sum find randperm type fliplr reshape whos flipud rng zeros fminsearch save full size
-1 -0.5 0 0.5 1
-0.
-0.
-0.
-0.
0