Professional Documents
Culture Documents
When you start MATLAB, by default, MATLAB automatically loads all the program files provided by MathWorks for MATLAB and other MathWorks products. You do not have to start each product you want to use. There are alternative ways to start MATLAB, and you can customize MATLAB startup. For example, you can change the folder in which MATLAB starts or automatically execute MATLAB statements upon startup.
The Desktop
When you start MATLAB, the desktop appears, containing tools (graphical user interfaces) for managing files, variables, and applications associated with MATLAB.
Fundamental Expressions/Operations
MATLAB uses conventional decimal notion, builds expressions with the usual arithmetic operators and precedence rules: x = 3.421 x= 3.4210
p = sin(pi/2) p= 1
Entering Matrices
The best way for you to get started with MATLAB is to learn how to handle matrices. Start MATLAB and follow along with each example. You can enter matrices into MATLAB in several different ways: Enter an explicit list of elements. Load matrices from external data files. Generate matrices using built-in functions. Create matrices with your own functions and save them in files.
You only have to follow a few basic conventions: Separate the elements of a row with blanks or commas. Use a semicolon, ; , to indicate the end of each row. Surround the entire list of elements with square brackets, [ ].
Matrix Operations
Matrix operations are fundamental to MATLAB. Within a matrix, columns are separated by space, and the rows are separated by semicolon;. For example A = [1 2 3; 4 5 6; 7 8 9] A= 1 4 7 2 5 8 3 6 9
A' ans = 1 2 3 4 5 6 7 8 9
The following matrix operations are available in MATLAB: + * / addition matrix multiplication ^ transpose right division power \ left division subtraction
The operations, , ^, \, and /, can be made to operate entry-wise by preceding them by a period.
Building Matrix
Convenient matrix building functions are eye identity matrix ones matrix of ones triu rand A = eye(3) A= 1 0 0 0 1 0 0 0 1 upper triangular part of a matrix randomly generated matrix zeros matrix of zeros diag tril diagonal matrix lower triangular part of a matrix
B = zeros(3,2) B= 0 0 0 0 0 0
0.6068 Matrices can be built from blocks. For example, D = [A B C D] D= 1.0000 0 0 0 0 0 0 0 0 0 0 0 0.9501 0.2311 0.6068
1.0000 0
1.0000
D(1,6) ans = 0.9501 Other functions for colon notation: E = 0.3:0.4:1.5 E= 0.3000 0.7000 1.1000 1.5000
Vector Functions
Certain functions in MATLAB are vector functions, i.e., they operate essentially on a vector (row or column). For example, the maximum entry in a matrix D is given by max(max(D)). max(D) ans = 1.0000 1.0000 1.0000 0 0 0.9501
max(max(D)) ans = 1
A few of these functions are: max, min, sort, sum, prod, mean, std, any, all.
Matrix functions
The most useful matrix functions are eig inv size eigenvalues and eigenvectors inverse size svd det rank singular value decomposition determinant rank
For example F = rand(3,3) F= 0.4860 0.8913 0.7621 eig(F) ans = 1.7651 0.0310 -0.4997 rank(F) ans = 3 inv(F) ans = 17.9446 -0.1385 -9.9689 8.6579 -1.6802 -3.5560 -26.2485 1.8760 14.5444 0.4565 0.0185 0.8214 0.4447 0.6154 0.7919
Subscript expressions involving colons refer to portions of a matrix: F(1:k,j) is the first k elements of the jth column of A. Thus: sum(F(1:3,3)) computes the sum of the fourth column. However, there is a better way to perform this computation. The colon by itself refers to all the elements in a row or column of a matrix and the keyword end refers to the last row or column. Thus: sum(F(:,end)) Determinant: Inverse: d = det(A) c=inv(A)
Arrays
When they are taken away from the world of linear algebra, matrices become two-dimensional numeric arrays. Arithmetic operations on arrays are done element by element. This means that addition and subtraction are the same for arrays and matrices, but that multiplicative operations are different. MATLAB uses a dot, or decimal point, as part of the notation for multiplicative array operations. The list of operators includes: + .* .\ .' Addition Element-by-element multiplication Element-by-element left division Unconjugated array transpose ./ .^ Subtraction
Relational Operators
Relational operators compare operands quantitatively, using operators like "less than" and "not equal to." The following table provides a summary. For more information, see the relational operators reference page. < Less than > Greater than == Equal to <= >= ~= Less than or equal to Greater than or equal to Not equal to
ans = 0 0 0 1 0 0 0 1 0
For vectors and rectangular arrays, both operands must be the same size unless one is a scalar. For the case where one operand is a scalar and the other is not, MATLAB tests the scalar against every element of the other operand. Locations where the specified relation is true receive logical 1. Locations where the relation is false receive logical 0.
Logical Operators
MATLAB offers three types of logical operators and functions: Element-wise operate on corresponding elements of logical arrays. Bit-wise operate on corresponding bits of integer values or arrays. Short-circuit operate on scalar, logical expressions. The values returned by MATLAB logical operators and functions, with the exception of bit-wise functions, are of type logical and are suitable for use with logical indexing. Element-Wise Operators and Functions The following logical operators and functions perform elementwise logical operations on their inputs to produce a like-sized output array.The examples shown in the following table use vector inputs A and B, where A = [0 1 1 0 1]; B = [1 1 0 0 1];
Op erator & Description Example
Returns 1 for every element location that is true (nonzero) in both arrays, and 0 for all other elements. Returns 1 for every element location that is true (nonzero) in either one or the other, or both arrays, and 0 for all other elements. Complements each element of the input array, A. Returns 1 for every element location that is true (nonzero) in only one array, and 0 for all other elements.
~ xor
For operators and functions that take two array operands, (&, |, and xor), both arrays must have equal dimensions, with each dimension being the same size. The one exception to this is where one operand is a scalar and the other is not. In this case, MATLAB tests the scalar against every element of the other operand.
Operator Overloading
You can overload the &, |, and ~ operators to make their behavior dependent upon the class on which they are being used. Each of these operators has a representative function that is called whenever that operator is used. These are shown in the table below.
Short-Circuit Operators
The following operators perform AND and OR operations on logical expressions containing scalar values. They are short-circuit operators in that they evaluate their second operand only when the result is not fully determined by the first operand.
Operator Description && || Returns logical 1 (true) if both inputs evaluate to true, and logical 0 (false) if they do not. Returns logical 1 (true) if either input, or both, evaluate to true, and logical 0 (false) if they do not.
The statement shown here performs an AND of two logical terms, A and B: A && B If A equals zero, then the entire expression will evaluate to logical 0 (false), regardless of the value of B. Under these circumstances, there is no need to evaluate B because the result is already known. In this case, MATLAB short-circuits the statement by evaluating only the first term. A similar case is when you OR two terms and the first term is true. Again, regardless of the value of B, the statement will evaluate to true. There is no need to evaluate the second term, and MATLAB does not do so.
Operator Precedence
You can build expressions that use any combination of arithmetic, relational, and logical operators. Precedence levels determine the order in which MATLAB evaluates an expression. Within each precedence level, operators have equal precedence and are evaluated from left to right. The precedence rules for MATLAB operators are shown in this list, ordered from highest precedence level to lowest precedence level:
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
Parentheses () Transpose (.'), power (.^), complex conjugate transpose ('), matrix power (^) Unary plus (+), unary minus (-), logical negation (~) Multiplication (.*), right division (./), left division (.\), matrix multiplication (*), matrix right division (/), matrix left division (\) Addition (+), subtraction (-) Colon operator (:) Less than (<), less than or equal to (<=), greater than (>), greater than or equal to (>=), equal to (==), not equal to (~=) Element-wise AND (&) Element-wise OR (|) Short-circuit AND (&&) Short-circuit OR (||)
Multivariate Data
MATLAB uses column-oriented analysis for multivariate statistical data. Each column in a data set represents a variable and each row an observation. The (i,j)th element is the ith observation of the jth variable. For five observations, the resulting array might look like
D=
[ 72 81 69 82 75
The first row contains the heart rate, weight, and exercise hours for patient 1, the second row contains the data for patient 2, and so on. Now you can apply many MATLAB data analysis functions to this data set. For example, to obtain the mean and standard deviation of each column, use mu = mean(D), mu = 75.8 sigma = 5.6303 25.499 2.2107 161.8 3.48 sigma = std(D)
3ff5555555555555 3eb4b6231abfd271
M-files
MATLAB can execute a sequence of statements in a file. Such files are called M-files because they must have the file type of .m as the last part of their filename. There are two types of M -files: script files and function files. Script files A script file consists of a sequence of normal MATLAB statements. For example, type all the commands for generating the figure into a single script file and save as sineplot.m. Then the MATLAB command sineplot will cause the statements in the file to be executed. Try it.
10
Function files You can create new functions specific to your problem, which will then have the same status as other MATLAB functions. Variables in a function files are by default local, otherwise need to be declared as global. The function file will start with function *y1, y2, ..+ = Function Name (x1, x2, ) Here is a simple example. The file myrand.m contains the statements function x = myrand(l, u, row, col) % generate uniformly-distributed random number matrix (row, col) between low% bound l and upper-bound u. x = l + rand(row, col).* (u-l); We would like to generate a 2 by 3 random matrix between 1.5 and 4.5 a = myrand(1.5, 4.5, 2, 3) a= 4.2654 3.7146 2.0288 2.7171 4.3064 4.2507
Programming
Flow Control if, else, and elseif
if expression, statements, end evaluates expression and, if the evaluation yields logical 1 (true) or a nonzero result, executes one or more MATLAB commands denoted here as statements. expression is a MATLAB expression, usually consisting of variables or smaller expressions joined by relational operators (e.g., count < limit), or logical functions (e.g., isreal(A)). Simple expressions can be combined by logical operators (&&, ||, ~) into compound expressions such as the following. MATLAB evaluates compound expressions from left to right, adhering to operator precedence rules. (count < limit) && ((height - offset) >= 0) Nested if statements must each be paired with a matching end. The if function can be used alone or with the else and elseif functions. When using elseif and/or else within an if statement, the general form of the statement is if expression1 statements1 elseif expression2 statements2 else statements3 end
11
See Program Control Statements in the MATLAB Programming Fundamentals documentation for more information on controlling the flow of your program code. Within the context of an if or while expression, MATLAB does not necessarily evaluate all parts of a logical expression. In some cases it is possible, and often advantageous, to determine whether an expression is true or false through only partial evaluation. For example, if A equals zero in statement 1 below, then the expression evaluates to false, regardless of the value of B. In this case, there is no need to evaluate B and MATLAB does not do so. In statement 2, if A is nonzero, then the expression is true, regardless of B. Again, MATLAB does not evaluate the latter part of the expression. 1) if (A && B) 2) if (A || B)
You can use this property to your advantage to cause MATLAB to evaluate a part of an expression only if a preceding part evaluates to the desired state. Here are some examples. while (b ~= 0) && (a/b > 18.5) if exist('myfun.m') && (myfun(x) >= y) if iscell(A) && all(cellfun('isreal', A)) Empty Arrays In most cases, using if on an empty array treats the array as false. There are some conditions however under which if evaluates as true on an empty array. Two examples of this, where A is equal to [], are if all(A), do_something, end if 1|A, do_something, end The latter expression is true because of short-circuiting, which causes MATLAB to ignore the right side operand of an OR statement whenever the left side evaluates to true.
else
if expression, statements1, else statements2, end evaluates expression and, if the evaluation yields logical 1 (true) or a nonzero result, executes one or more MATLAB commands denoted here as statements1 or, if the evaluation yields logical 0 (false), executes the commands in statements2. else is used to delineate the alternate block of statements.. A true expression has either a logical 1 (true) or nonzero value. For nonscalar expressions, (for example, "if (matrix A is less than matrix B)"), true means that every element of the resulting matrix has a true or nonzero value. Expressions usually involve relational operations such as (count < limit) or isreal(A). Simple expressions can be combined by logical operators (&,|,~) into compound expressions such as (count < limit) & ((height - offset) >= 0). See Program Control Statements in the MATLAB Programming Fundamentals documentation for more information on controlling the flow of your program code.
elseif if expression1, statements1, elseif expression2, statements2, end evaluates expression1 and, if the evaluation yields logical 1 (true) or a nonzero result, executes one or more MATLAB commands denoted here as statements1. If expression1 is false, MATLAB evaluates the elseif expression, expression2. If expression2 evaluates to true or a nonzero result, executes the commands in statements2. A true expression has either a logical 1 (true) or nonzero value. For nonscalar expressions, (for example, is matrix A less then matrix B), true means that every element of the resulting matrix has a true or nonzero value.
12
Expressions usually involve relational operations such as (count < limit) or isreal(A). Simple expressions can be combined by logical operators (&,|,~) into compound expressions such as (count < limit) & ((height - offset) >= 0). See Program Control Statements in the MATLAB Programming Fundamentals documentation for more information on controlling the flow of your program code. The commands else and if, with a space or line break between them, differ from elseif, with no space. The former introduces a new, nested if that requires a matching end statement. The latter is used in a linear sequence of conditional statements with only one terminating end. The two segments shown below produce identical results. Exactly one of the four assignments to x is executed, depending upon the values of the three logical expressions, A, B, and C. if A x=a else if B x=b else if C x=c else x=d end end end end else x=d elseif C x=c elseif B x=b if A x=a
for for index = values program statements : end repeatedly executes one or more MATLAB statements in a loop. values has one of the following forms: initval:endval increments the index variable from initval to endval by 1, and repeats execution of program statements until index is greater than endval. initval:step:endval is negative. increments index by the value step on each iteration, or decrements when step
valArray creates a column vector index from subsequent columns of array valArray on each iteration. For example, on the first iteration, index = valArray(:,1). The loop executes for a maximum of n times, where n is the number of columns of valArray, given by numel(valArray, 1, :). To force an immediate exit of the loop, use a break or return statement. To skip the rest of the instructions in the loop, increment the loop counter, and begin the next iteration, use a continue statement.
13
Avoid assigning a value to the index variable within the body of a loop. The for statement overrides any changes made to the index within the loop. To iterate over the values of a single column vector, first transpose it to create a row vector. Examples: Create a Hilbert matrix using nested for loops: k = 10; hilbert = zeros(k,k); for m = 1:k for n = 1:k hilbert(m,n) = 1/(m+n -1); end end Step by increments of -0.1, and display the step values: for s = 1.0: -0.1: 0.0 disp(s) end % Preallocate matrix
Execute statements for a defined set of index values: for s = [1,5,8,17] disp(s) end Successively set e to unit vectors: for e = eye(5) disp('Current value of e:') disp(e) end
Here is an example showing if, else, and elseif. for m = 1:k for n = 1:k if m == n a(m,n) = 2; elseif abs(m-n) == 2 a(m,n) = 1; else
14
a(m,n) = 0; end end end For k=5 you get the matrix a= 2 0 1 0 0 0 2 0 1 0 1 0 2 0 1 0 1 0 2 0 0 0 1 0 2
While
while expression program statements : end repeatedly executes one or more MATLAB program statements in a loop, continuing until expression no longer holds true or until MATLAB encounters a break, or return instruction, thus forcing an immediate exit of the loop code. If MATLAB encounters a continue statement in the loop code, it interrupts execution of the loop code at the location of the continue statement, and begins another iteration of the loop at the while expression statement. expression is a MATLAB expression that evaluates to a result of logical 1 (true) or logical 0 (false). expression can be scalar or an array. It must contain all real elements, and the statement all(A(:)) must be equal to logical 1 for the expression to be true. expression usually consists of variables or smaller expressions joined by relational operators (e.g., count < limit) or logical functions (e.g., isreal(A)). Simple expressions can be combined by logical operators (&&, ||, ~) into compound expressions such as the following. MATLAB evaluates compound expressions from left to right, adhering to Operator Precedence rules. (count < limit) && ((height - offset) >= 0) statements is one or more MATLAB statements to be executed only while the expression is true or nonzero. The scope of a while statement is always terminated with a matching end. Examples The variable eps is a tolerance used to determine such things as near singularity and rank. Its initial value is the machine epsilon, the distance from 1.0 to the next largest floating-point number on your machine. Its calculation demonstrates while loops. eps = 1; while (1+eps) > 1 eps = eps/2;
15
end eps = eps*2 This example is for the purposes of illustrating while loops only and should not be executed in your MATLAB session. Doing so will disable the eps function from working in that session.
16
Text Files
csvread csvwrite dlmread dlmwrite fileread textread textscan type Read comma-separated value file Write comma-separated value file Read ASCII-delimited file of numeric data into matrix Write matrix to ASCII-delimited file Read contents of file into string Read data from text file; write to multiple outputs Read formatted data from text file or string Display contents of file
Microsoft Excel
xlsfinfo xlsread xlswrite Determine whether file contains Microsoft Excel spreadsheet Read Microsoft Excel spreadsheet file Write Microsoft Excel spreadsheet file
Plotting Figures
Creating a Figure If y is a vector, plot (y) produces a linear graph of the elements of y versus the index of the elements of y. If you specify two vectors as arguments, plot(x,y) produces a graph of y versus x. t = 0:pi/100:2*pi; x = sin(t); y1 = sin(t+0.25); y2 = cos(t-0.25); figure(1) % open a figure and make it current, not necessarily plot(x,y1,'r-',x,y2, 'g--') title('sin-cos plots') xlabel('x=sin(t)') ylabel('y') By plotting multiple figures on the graph, one alternative way is to use hold on and hold off commands, plot(x,y1, 'r-') hold on plot(x,y2, 'g--') hold off
17
Other types of plots: loglog semilogx semilogy plot using logarithmic scales for both axes plot using a logarithmic scales for x-axis and linear scale for the y-axis figure out yourself
Line styles, markers, and color Symbol y m c r g b w k Color yellow magenta cyan red green blue white black Symbol . o x + * : -. -Exporting a Figure 1) Cut and paste: click Edit at the top menu bar of the figure window, then click Copy Figure, paste the figure wherever you want. 2) Save as a file: print tiff deps (print as a postscript file). Type help print to find out more options. The MATLAB hold command enables you to add plots to an existing graph. When you type hold on Now MATLAB does not replace the existing graph when you issue another plotting command; it adds the new data to the current graph, rescaling the axes if necessary. For example, these statements first create a contour plot of the peaks function, then superimpose a pseudocolor plot of the same function: [x,y,z] = peaks; pcolor(x,y,z) shading interp hold on contour(x,y,z,20,'k') hold off The hold on command combines the pcolor plot with the contour plot in one figure. Linestyle point circle x-mark plus star solid dotted dashdot dashed
18
3D plotting
When you make a 3-dimensional plot, you usually have a z variable that is a function of both x and y. When you want x and y to vary over some range, you need a matrix (rather than a vector) for x and y to get a complete domain that covers all the different combinations of those x and y values over some range. A function called meshgrid will set up x and y matrixes like this for you. The x matrix varies the x down rows and keeps it constant in columns, and the y matrix varies the y in columns and keeps it constant across rows, so you get all combinations of x and y if you use the two matrices. To get a rectangular domain that goes from x=1 to x=10 in steps of .5, and from y=1 to y=10 in steps of .5 using meshgrid, you can use [x, y] = meshgrid([1:.5:10],[1:.5:10]); Then, you can do a 3d plot by caculating some z values on the x and y domains, and doing a surface, mesh, or contour plot. z = x.^2 - y.^2 surf(x,y,z) mesh(x,y,z) contour(x,y,z) You could also use surfc or meshc to get surface or mesh plots with a contour plot drawn on the x-y plane. Surface plots and mesh plots color the plots according to the z value, by default. You can use some other equallysized matrix to get the coloring instead by adding that matrix as an extra argument, like: c = x.^2 + y.^2; mesh(x,y,z,c)
Bar Charts
2D bar graphs plot data points in terms of their area. Given some random data: xBar=[1:10]; yBar=rand(1,10) * 100; a bar chart is produced using: bar(xBar,yBar); 2D bar charts can also be created for matrices, in which case each row in the matrix is considered as one group of bars. The resulting graph distinguishes matrix columns with different colors. yBar=rand(7,3); bar(yBar); 3D bar graphs are easily obtained from matrices as well, using the bar3 command: bar3(yBar)
19
z=[]; for i=1:100 for j=1:100 z(i,j) = sin(i/10) + cos(j/10); end end mesh(z); creates a mesh (with holes) next command creates a mesh with filled patches (a surface). surf(z); For the data set of gasoline prices per region, a viable mesh would be: mesh(data);
Multiple plots
Using the subplot function, it is possible to generate separate plots in a grid of figures. SUBPLOT(M, N, P) creates a grid of figures for M rows, N columns, and fills the Pth cell with the next figure. Example: subplot(3, 2, 1), plot(rand(1, 10)); subplot(3, 2, 2), bar(rand(1, 10)); subplot(3, 2, 3), surf(rand(20)); subplot(3, 2, 4), hist(rand(50)); subplot(3, 2, 5), plot(sin([0:0.1:10])); subplot(3, 2, 6), plot(rand(1,100),'gd:');
20