SELAMAT DATANG DI BLOG SAYA

Selasa, 19 Juni 2012

simbol analisa numerik

TUGAS MATA KULIAH
ANALISA NUMERIK










TUGAS
Fungsi - Fungsi MATLAB


ANDRIE AWALUDIN HT
NPM : 13110013









Jurusan Teknik Elektro
Universitas Batam
Batam 2011





abs -Absolute value and complex magnitude
Syntax
abs(X)
Description
abs(X) returns an array Y such that each element of Y is the absolute value of the corresponding element of X.
If X is complex, abs(X) returns the complex modulus (magnitude), which is the same as
sqrt(real(X).^2 + imag(X).^2)
Examples
abs(-5)
ans =
5

abs(3+4i)
ans = 5

all -Determine whether all array elements are nonzero or true
Syntax
B = all(A)
B = all(A, dim)
Description
B = all(A) tests whether all the elements along various dimensions of an array are nonzero or logical 1 (true).
If A is empty, all(A) returns logical 1 (true).
If A is a vector, all(A) returns logical 1 (true) if all the elements are nonzero and returns logical 0 (false) if one or more elements are zero.
If A is a matrix, all(A) treats the columns of A as vectors, returning a row vector of logical 1's and 0's.
If A is a multidimensional array, all(A) treats the values along the first nonsingleton dimension as vectors, returning a logical condition for each vector.
B = all(A, dim) tests along the dimension of A specified by scalar dim.

Examples
Given
A = [0.53 0.67 0.01 0.38 0.07 0.42 0.69]
then B = (A < 0.5) returns logical 1 (true) only where A is less than one half: 0 0 1 1 1 1 0 The all function reduces such a vector of logical conditions to a single condition. In this case, all(B) yields 0. This makes all particularly useful in if statements: if all(A < 0.5) do something end where code is executed depending on a single condition, not a vector of possibly conflicting conditions. Applying the all function twice to a matrix, as in all(all(A)), always reduces it to a scalar condition. all(all(eye(3))) ans = 0 any -Determine whether any array elements are nonzero Syntax B = any(A) B = any(A,dim) Description B = any(A) tests whether any of the elements along various dimensions of an array is a nonzero number or is logical 1 (true). The any function ignores entries that are NaN (Not a Number). If A is empty, any(A) returns logical 0 (false). If A is a vector, any(A) returns logical 1 (true) if any of the elements of A is a nonzero number or is logical 1 (true), and returns logical 0 (false) if all the elements are zero. If A is a matrix, any(A) treats the columns of A as vectors, returning a row vector of logical 1's and 0's. If A is a multidimensional array, any(A) treats the values along the first nonsingleton dimension as vectors, returning a logical condition for each vector. B = any(A,dim) tests along the dimension of A specified by scalar dim. Examples Example 1 – Reducing a Logical Vector to a Scalar Condition Given A = [0.53 0.67 0.01 0.38 0.07 0.42 0.69] then B = (A < 0.5) returns logical 1 (true) only where A is less than one half: 0 0 1 1 1 1 0 The any function reduces such a vector of logical conditions to a single condition. In this case, any(B) yields logical 1. This makes any particularly useful in if statements: if any(A < 0.5)do something end where code is executed depending on a single condition, not a vector of possibly conflicting conditions. Example 2– Reducing a Logical Matrix to a Scalar Condition Applying the any function twice to a matrix, as in any(any(A)), always reduces it to a scalar condition. any(any(eye(3))) ans = 1 Example 3 – Testing Arrays of Any Dimension You can use the following type of statement on an array of any dimensions. This example tests a 3-D array to see if any of its elements are greater than 3: x = rand(3,7,5) * 5; any(x(:) > 3)
ans =
1
or less than zero:
any(x(:) < 0) ans = 0 axis -Axis scaling and appearance Syntax axis([xmin xmax ymin ymax]) axis([xmin xmax ymin ymax zmin zmax cmin cmax]) v = axis axis auto axis manual axis tight axis fill axis ij axis xy axis equal axis image axis square axis vis3d axis normal axis off axis on axis(axes_handles,...) [mode,visibility,direction] = axis('state') Description axis manipulates commonly used axes properties. (See Algorithm section.) axis([xmin xmax ymin ymax]) sets the limits for the x- and y-axis of the current axes. axis([xmin xmax ymin ymax zmin zmax cmin cmax]) sets the x-, y-, and z-axis limits and the color scaling limits (see caxis) of the current axes. v = axis returns a row vector containing scaling factors for the x-, y-, and z-axis. v has four or six components depending on whether the current axes is 2-D or 3-D, respectively. The returned values are the current axes XLim, Ylim, and ZLim properties. axis auto sets MATLAB default behavior to compute the current axes limits automatically, based on the minimum and maximum values of x, y, and zdata. You can restrict this automatic behavior to a specific axis. For example, axis 'auto x' computes only the x-axis limits automatically; axis 'auto yz' computes the y- and z-axis limits automatically. axis manual and axis(axis) freezes the scaling at the current limits, so that if hold is on, subsequent plots use the same limits. This sets theXLimMode, YLimMode, and ZLimMode properties to manual. axis tight sets the axis limits to the range of the data. axis fill sets the axis limits and PlotBoxAspectRatio so that the axes fill the position rectangle. This option has an effect only ifPlotBoxAspectRatioMode or DataAspectRatioMode is manual. axis ij places the coordinate system origin in the upper left corner. The i-axis is vertical, with values increasing from top to bottom. The j-axis is horizontal with values increasing from left to right. axis xy draws the graph in the default Cartesian axes format with the coordinate system origin in the lower left corner. The x-axis is horizontal with values increasing from left to right. The y-axis is vertical with values increasing from bottom to top. axis equal sets the aspect ratio so that the data units are the same in every direction. The aspect ratio of the x-, y-, and z-axis is adjusted automatically according to the range of data units in the x, y, and z directions. axis image is the same as axis equal except that the plot box fits tightly around the data. axis square makes the current axes region square (or cubed when three-dimensional). This option adjusts the x-axis, y-axis, and z-axis so that they have equal lengths and adjusts the increments between data units accordingly. axis vis3d freezes aspect ratio properties to enable rotation of 3-D objects and overrides stretch-to-fill. axis normal automatically adjusts the aspect ratio of the axes and the relative scaling of the data units so that the plot fits the figure's shape as well as possible. axis off turns off all axis lines, tick marks, and labels. axis on turns on all axis lines, tick marks, and labels. axis(axes_handles,...) applies the axis command to the specified axes. For example, the following statements h1 = subplot(221); h2 = subplot(222); axis([h1 h2],'square') set both axes to square. [mode,visibility,direction] = axis('state') returns three strings indicating the current setting of axes properties: Output Argument Strings Returned mode 'auto' | 'manual' visibility 'on' | 'off' direction 'xy' | 'ij' mode is auto if XLimMode, YLimMode, and ZLimMode are all set to auto. If XLimMode, YLimMode, or ZLimMode is manual, mode is manual. Keywords to axis can be combined, separated by a space (e.g., axis tight equal). These are evaluated from left to right, so subsequent keywords can overwrite properties set by prior ones. Tips You can create an axes (and a figure for it) if none exists with the axis command. However, if you specify non-default limits or formatting for the axes when doing this, such as [4 8 2 9], square, equal, or image, the property is ignored because there are no axis limits to adjust in the absence of plotted data. To use axis in this manner, you can set hold on to keep preset axes limits from being overridden. Examples The statements x = 0:.01:pi/2; plot(x,tan(x),'-ro') use the automatic scaling of the y-axis based on ymax = tan(1.57), which is well over 1000: The following figure shows a more satisfactory plot after typing axis([0 pi/2 0 5]) Algorithms When you specify minimum and maximum values for the x-, y-, and z-axes, axis sets the XLim, Ylim, and ZLim properties for the current axes to the respective minimum and maximum values in the argument list. Additionally, the XLimMode, YLimMode, and ZLimMode properties for the current axes are set to manual. axis auto sets the current axes XLimMode, YLimMode, and ZLimMode properties to 'auto'. axis manual sets the current axes XLimMode, YLimMode, and ZLimMode properties to 'manual'. The following table shows the values of the axes properties set by axis equal, axis normal, axis square, and axis image. Axes Property or Behavior axis equal axis normal axis square axis image DataAspectRatio property [1 1 1] not set not set [1 1 1] DataAspectRatioMode property manual auto auto manual PlotBoxAspectRatio property [3 4 4] not set [1 1 1] auto PlotBoxAspectRatioMode property manual auto manual auto Stretch-to-fill behavior; disabled active disabled disabled bar -Plot bar graph Alternatives To graph selected variables, use the Plot Selector in the Workspace Browser, or use the Figure Palette Plot Catalog. Manipulate graphs in plot edit mode with the Property Editor. For details, see Plotting Tools — Interactive Plotting in the MATLAB Graphics documentation andCreating Plots from the Workspace Browser in the MATLAB Desktop Tools and Development Environment documentation. Syntax bar(Y) bar(X,Y) bar(...,width) bar(...,'style') bar(...,'bar_color') bar(...,'PropertyName',PropertyValue,...) bar(axes_handle,...) h = bar(...) Description A bar graph displays the values in a vector or matrix as bars. bar(Y) draws one bar for each element in Y. If Y is a matrix, bar groups the bars produced by the elements in each row. When Y is a vector, the x-axis scale ranges from 1 up to length(Y). When Y is a matrix, x-axis scale ranges from 1 to size(Y,1). The default is to assign an appropriate progression of tick values according to the data. If you want the x-axis scale to end exactly at the last bar, you can use the default or type set(gca,'XLim',[1 length(Y)]) bar(X,Y) draws a bar for each element in Y at locations specified in X, where X is a vector defining the x-axis intervals for the vertical bars. The x-values can be nonmonotonic, but cannot contain duplicate values. If Y is a matrix, bar groups the elements of each row in Y at corresponding locations inX. bar(...,width) sets the relative bar width and controls the separation of bars within a group. The default width is 0.8, so if you do not specify X, the bars within a group have a slight separation. If width is 1, the bars within a group touch one another. The value of width must be a scalar. bar(...,'style') specifies the style of the bars. 'style' is 'grouped' or 'stacked'. Default mode of display is 'grouped'.  'grouped' displays m groups of n vertical bars, where m is the number of rows and n is the number of columns in Y. The group contains one bar per column in Y.  'stacked' displays one bar for each row in Y. The bar height is the sum of the elements in the row. Each bar is multicolored. Colors correspond to distinct elements and show the relative contribution each row element makes to the total sum.  'histc' displays the graph in histogram format, in which bars touch one another.  'hist' also displays the graph in histogram format, but centers each bar over the x-ticks, rather than making bars span x-ticks as the histc option does. Note When you use either the hist or histc option, you cannot also use parameter/value syntax. These two options create graphic objects that are patches rather than barseries. bar(...,'bar_color') displays all bars using the color specified by the single-letter abbreviation 'r', 'g', 'b', 'c', 'm', 'y', 'k', or 'w'. bar(...,'PropertyName',PropertyValue,...) sets the named property or properties to the specified values. You cannot specify properties when using hist or histc options. See the barseries property descriptions for information on what properties you can set. bar(axes_handle,...) plots into the axes with the handle axes_handle instead of into the current axes (gca). h = bar(...) returns a vector of handles to barseries graphics objects, one for each created. When Y is a matrix, bar creates one barseries graphics object per column in Y. Barseries Objects Creating a bar graph of an m-by-n matrix creates m groups of n barseries objects. Each barseries object contains the data for corresponding X values of each bar group (as indicated by the coloring of the bars). Note that some barseries object properties set on an individual barseries object set the values for all barseries objects in the graph. See the barseries property descriptions for information on specific properties. Examples Single Series of Data This example shows how to plot vector data using bar. y = [75.995 91.972 105.711 123.203 131.669 ... 150.697 179.323 203.212 226.505 249.633 281.422]; figure; bar(y); Specifying Width While Passing Single Variable. This example shows how to specify width for each bar in the graph. You can specify one or both data inputs. figure; bar(y,0.4); Specifying Style This example shows you how to specify style for bar graph. figure; subplot(2,2,1); bar(y,'grouped'); subplot(2,2,2); bar(y,'stacked'); subplot(2,2,3); bar(y,'hist'); subplot(2,2,4); bar(y,'histc'); Specifying Color This example shows how to specify color for the graph. figure; bar(y,'r'); Specifying Name-Value Pairs You can specify the rgb color instead of using the predefined ones. For Example, figure; bar(y,'g','EdgeColor',[1 0.5 0.5]); Passing Two Variables This example shows how to plot vector data with two inputs x and y using bar . x = [1900:10:2000]; figure; bar(x,y); y values are plotted against each x value. Note that the length(x) and length(y) have to be same. Setting Axis Scale The default is to assign an appropriate progression of tick values according to the data. If you want the y-axis scale to end exactly at the last bar, you can change the axes YLim property, which sets the limits of the y-axis. See axes for more information. x = [1900:10:2000]; figure; bar(x,y); set(gca,'YLim',[1 max(y)]); Passing an Expression You can also pass an expression with the bar function. a = -2.9:0.2:2.9; bar(a,exp(-a.*a),'r') Plotting Matrix Data This example shows how to plot matrix data using bar. load count.dat; yMat = count(1:6,:); figure; bar(yMat); Specifying Name-Value Pairs for Matrix Input This example shows how to set LineWidth and LineStyle for three barseries objects using the handle returned by bar. hMulti = bar(yMat); set(hMulti,'LineWidth', 2, 'LineStyle',':'); Setting Properties with Multiobject Graphs This example creates a graph that displays three groups of bars and contains five barseries objects. Since all barseries objects in a graph share the same baseline, you can set values using any barseries object's BaseLine property. This example uses the first handle returned in h. Y = randn(3,5); h = bar(Y); set(get(h(1),'BaseLine'),'LineWidth',2,'LineStyle',':') colormap summer % Change the color scheme Specifying colormap assigns a specific color in the map spectrum to each handle object in the group resulting in one color for each object group. break -Terminate execution of for or while loop Syntax break Description break terminates the execution of a for or while loop. Statements in the loop that appear after the break statement are not executed. In nested loops, break exits only from the loop in which it occurs. Control passes to the statement that follows the end of that loop. Tips break is not defined outside a for or while loop. Use return in this context instead. Examples The example below shows a while loop that reads the contents of the file fft.m into a MATLAB character array. A break statement is used to exit thewhile loop when the first empty line is encountered. The resulting character array contains the command line help for the fft program. fid = fopen('fft.m','r'); s = ''; while ~feof(fid) line = fgetl(fid); if isempty(line) || ~ischar(line), break, end s = sprintf('%s%s\n', s, line); end disp(s); fclose(fid); ceil -Round toward positive infinity Syntax B = ceil(A) Description B = ceil(A) rounds the elements of A to the nearest integers greater than or equal to A. For complex A, the imaginary and real parts are rounded independently. Examples a = [-1.9, -0.2, 3.4, 5.6, 7, 2.4+3.6i] a = Columns 1 through 4 -1.9000 -0.2000 3.4000 5.6000 Columns 5 through 6 7.0000 2.4000 + 3.6000i ceil(a) ans = Columns 1 through 4 -1.0000 0 4.0000 6.0000 Columns 5 through 6 7.0000 3.0000 + 4.0000i chol -Cholesky factorization Syntax R = chol(A) L = chol(A,'lower') [R,p] = chol(A) [L,p] = chol(A,'lower') [R,p,S] = chol(A) [R,p,s] = chol(A,'vector') [L,p,s] = chol(A,'lower','vector') Description R = chol(A) produces an upper triangular matrix R from the diagonal and upper triangle of matrix A, satisfying the equation R'*R=A. The lower triangle is assumed to be the (complex conjugate) transpose of the upper triangle. Matrix A must be positive definite; otherwise, MATLAB software displays an error message. L = chol(A,'lower') produces a lower triangular matrix L from the diagonal and lower triangle of matrix A, satisfying the equation L*L'=A. When A is sparse, this syntax of chol is typically faster. Matrix A must be positive definite; otherwise MATLAB displays an error message. [R,p] = chol(A) for positive definite A, produces an upper triangular matrix R from the diagonal and upper triangle of matrix A, satisfying the equationR'*R=A and p is zero. If A is not positive definite, then p is a positive integer and MATLAB does not generate an error. When A is full, R is an upper triangular matrix of order q=p-1 such that R'*R=A(1:q,1:q). When A is sparse, R is an upper triangular matrix of size q-by-n so that the L-shaped region of the first q rows and first q columns of R'*R agree with those of A. [L,p] = chol(A,'lower') for positive definite A, produces a lower triangular matrix L from the diagonal and lower triangle of matrix A, satisfying the equation L*L'=A and p is zero. If A is not positive definite, then p is a positive integer and MATLAB does not generate an error. When A is full, L is a lower triangular matrix of order q=p-1 such that L*L'=A(1:q,1:q). When A is sparse, L is a lower triangular matrix of size q-by-n so that the L-shaped region of the first q rows and first q columns of L*L' agree with those of A. The following three-output syntaxes require sparse input A. [R,p,S] = chol(A), when A is sparse, returns a permutation matrix S. Note that the preordering S may differ from that obtained from amd since cholwill slightly change the ordering for increased performance. When p=0, R is an upper triangular matrix such that R'*R=S'*A*S. When p is not zero, R is an upper triangular matrix of size q-by-n so that the L-shaped region of the first q rows and first q columns of R'*R agree with those of S'*A*S. The factor of S'*A*S tends to be sparser than the factor of A. [R,p,s] = chol(A,'vector'), when A is sparse, returns the permutation information as a vector s such that A(s,s)=R'*R, when p=0. You can use the'matrix' option in place of 'vector' to obtain the default behavior. [L,p,s] = chol(A,'lower','vector'), when A is sparse, uses only the diagonal and the lower triangle of A and returns a lower triangular matrix Land a permutation vector s such that A(s,s)=L*L', when p=0. As above, you can use the 'matrix' option in place of 'vector' to obtain a permutation matrix. Note Using chol is preferable to using eig for determining positive definiteness. Examples Example 1 The gallery function provides several symmetric, positive, definite matrices. A=gallery('moler',5) A = 1 -1 -1 -1 -1 -1 2 0 0 0 -1 0 3 1 1 -1 0 1 4 2 -1 0 1 2 5 C=chol(A) ans = 1 -1 -1 -1 -1 0 1 -1 -1 -1 0 0 1 -1 -1 0 0 0 1 -1 0 0 0 0 1 isequal(C'*C,A) ans = 1 For sparse input matrices, chol returns the Cholesky factor. N = 100; A = gallery('poisson', N); N represents the number of grid points in one direction of a square N-by-N grid. Therefore, A is by . L = chol(A, 'lower'); D = norm(A - L*L', 'fro'); The value of D will vary somewhat among different versions of MATLAB but will be on order of . Example 2 The binomial coefficients arranged in a symmetric array create a positive definite matrix. n = 5; X = pascal(n) X = 1 1 1 1 1 1 2 3 4 5 1 3 6 10 15 1 4 10 20 35 1 5 15 35 70 This matrix is interesting because its Cholesky factor consists of the same coefficients, arranged in an upper triangular matrix. R = chol(X) R = 1 1 1 1 1 0 1 2 3 4 0 0 1 3 6 0 0 0 1 4 0 0 0 0 1 Destroy the positive definiteness (and actually make the matrix singular) by subtracting 1 from the last element. X(n,n) = X(n,n)-1 X = 1 1 1 1 1 1 2 3 4 5 1 3 6 10 15 1 4 10 20 35 1 5 15 35 69 Now an attempt to find the Cholesky factorization of X fails. chol(X) Error using chol Matrix must be positive definite. clc -Clear Command Window Alternatives As an alternative to the clc function, select Edit > Clear Command Window in the MATLAB desktop.
Syntax
clc
Description
clc clears all input and output from the Command Window display, giving you a "clean screen."
After using clc, you cannot use the scroll bar to see the history of functions, but you still can use the up arrow to recall statements from the command history.
Examples
Use clc in a MATLAB code file to always display output in the same starting position on the screen.


clear -Clear breakpoints from model
Syntax
clear
clear m:mid
clear id
clear

Short Form
cl
Arguments
mid Method ID
id Breakpoint ID
sysIdx:blkIdx Block ID
gcb Currently selected block
Description
clear clears a breakpoint from the current method.
clear m:mid clears a breakpoint from the method specified by mid.
clear id clears the breakpoint specified by the breakpoint ID id.
clear sysIdx:blkIdx clears any breakpoints set on the methods of the block specified by sysIdx:blkIdx.
clear gcb clears any breakpoints set on the methods of the currently selected block.


clock -Current time as date vector
Syntax
c = clock
Description
c = clock returns a 6-element date vector containing the current date and time in decimal form:
[year month day hour minute seconds]
Tips
 The sixth element of the date vector output (seconds) is accurate to several digits beyond the decimal point. The statement fix(clock) rounds to integer display format.
 When timing the duration of an event, use the tic and toc functions instead of clock or etime. These latter two functions are based on the system time which can be adjusted periodically by the operating system and thus might not be reliable in time comparison operations.

compan -Companion matrix
Syntax
A = compan(u)
Description
A = compan(u) returns the corresponding companion matrix whose first row is -u(2:n)/u(1), where u is a vector of polynomial coefficients. The eigenvalues of compan(u) are the roots of the polynomial.
Examples
The polynomial has a companion matrix given by
u = [1 0 -7 6]
A = compan(u)
A =
0 7 -6
1 0 0
0 1 0
The eigenvalues are the polynomial roots:
eig(compan(u))

ans =
-3.0000
2.0000
1.0000
This is also roots(u).


conj -Complex conjugate
Syntax
ZC = conj(Z)
Description
ZC = conj(Z) returns the complex conjugate of the elements of Z.
Algorithms
If Z is a complex array:
conj(Z) = real(Z) - i*imag(Z)


conv -Convolution and polynomial multiplication
Syntax
w = conv(u,v)
w = conv(...,'shape')
Description
w = conv(u,v) convolves vectors u and v. Algebraically, convolution is the same operation as multiplying the polynomials whose coefficients are the elements of u and v.
w = conv(...,'shape') returns a subsection of the convolution, as specified by the shape parameter:
full Returns the full convolution (default).
same Returns the central part of the convolution of the same size as u.
valid Returns only those parts of the convolution that are computed without the zero-padded edges. Using this option,length(w) is max(length(u)-max(0,length(v)-1),0).
Definitions
Let m = length(u) and n = length(v) . Then w is the vector of length m+n-1 whose kth element is

The sum is over all the values of j which lead to legal subscripts for u(j) and v(k+1-j), specifically j = max(1,k+1-n): min(k,m). When m = n, this gives
w(1) = u(1)*v(1)
w(2) = u(1)*v(2)+u(2)*v(1)
w(3) = u(1)*v(3)+u(2)*v(2)+u(3)*v(1)
...
w(n) = u(1)*v(n)+u(2)*v(n-1)+ ... +u(n)*v(1)
...
w(2*n-1) = u(n)*v(n)

cumprod -Cumulative product
Syntax
B = cumprod(A)
B = cumprod(A,dim)
Description
B = cumprod(A) returns the cumulative product along different dimensions of an array.
If A is a vector, cumprod(A) returns a vector containing the cumulative product of the elements of A.
If A is a matrix, cumprod(A) returns a matrix the same size as A containing the cumulative products for each column of A.
If A is a multidimensional array, cumprod(A) works on the first nonsingleton dimension.
B = cumprod(A,dim) returns the cumulative product of the elements along the dimension of A specified by scalar dim. For example, cumprod(A,1)increments the column index, thus working along the columns of A. Thus, cumprod(A,1) and cumprod(A) will return the same thing. To increment the row index, use cumprod(A,2).
Examples
cumprod(1:5)
ans =
1 2 6 24 120

A = [1 2 3; 4 5 6];

cumprod(A,1)
ans =
1 2 3
4 10 18

cumprod(A,2)
ans =
1 2 6
4 20 120


cumsum -Cumulative sum
Syntax
B = cumsum(A)
B = cumsum(A,dim)
Description
B = cumsum(A) returns the cumulative sum along different dimensions of an array.
If A is a vector, cumsum(A) returns a vector containing the cumulative sum of the elements of A.
If A is a matrix, cumsum(A) returns a matrix the same size as A containing the cumulative sums for each column of A.
If A is a multidimensional array, cumsum(A) works on the first nonsingleton dimension.
B = cumsum(A,dim) returns the cumulative sum of the elements along the dimension of A specified by scalar dim. For example, cumsum(A,1) works along the first dimension (the columns); cumsum(A,2) works along the second dimension (the rows).
Examples
cumsum(1:5)
ans =
[1 3 6 10 15]

A = [1 2 3; 4 5 6];

cumsum(A,1)
ans =
1 2 3
5 7 9

cumsum(A,2)
ans =
1 3 6
4 9 15

date -Current date string
Syntax
str = date
Description
str = date returns a string containing the date in dd-mmm-yyyy format.


deconv -Deconvolution and polynomial division
Syntax
[q,r] = deconv(v,u)
Description
[q,r] = deconv(v,u) deconvolves vector u out of vector v, using long division. The quotient is returned in vector q and the remainder in vector r such that v = conv(u,q)+r .
If u and v are vectors of polynomial coefficients, convolving them is equivalent to multiplying the two polynomials, and deconvolution is polynomial division. The result of dividing v by u is quotient q and remainder r.
Examples
If
u = [1 2 3 4]
v = [10 20 30]
the convolution is
c = conv(u,v)
c =
10 40 100 160 170 120
Use deconvolution to recover u:
[q,r] = deconv(c,u)
q =
10 20 30
r =
0 0 0 0 0 0
This gives a quotient equal to v and a zero remainder.
Algorithms
deconv uses the filter primitive.


delete -Remove files or graphics objects
Alternatives
As an alternative to the delete function, use the Current Folder browser.
Syntax
delete('fileName1', 'filename2', ...)
delete(h)
delete(handle_array)
delete fileName
Description
delete('fileName1', 'filename2', ...) deletes the files fileName1, fileName2, and so on, from the disk. fileName is a string and can be an absolute path or a path relative to the current folder. fileName also can include wildcards (*).
delete(h) deletes the graphics object with handle h. h can also be a vector or matrix of handles. Delete multiple objects by appending their handles as additional arguments, separated by commas. The function deletes objects without requesting verification, even if when they are windows.
delete(handle_array) is a method of the handle class. It removes from memory the handle objects referenced by handle_array.
When deleted, any references to the objects in handle_array become invalid. To remove the handle variables, use the clear function.
delete fileName is the command syntax. Delete multiple files by appending filenames, separated by spaces. When filenames contain space characters, you must use the functional form.
As delete does not ask for confirmation, to avoid accidentally losing files or graphics objects, make sure to specify accurately the items to delete. To move files to a different location when running delete, use the General preference for Deleting files, or the recycle function.
The delete function deletes files and graphics objects only. To delete folders, use rmdir.
Examples
Delete all files with a .mat extension in the ../mytests/ folder:
delete('../mytests/*.mat')
Create a figure and an axes, and then delete the axes:
hf = figure, ha = axes

hf =
1
ha =
170.0332

delete(ha)
The axes is deleted, but the figure remain. The axes handle ha remains in the workspace but no longer points to an object.

demo -Access product demos via Help browser
Alternatives
Select Help > Demos from any desktop tool.
Syntax
demo
demo 'subtopic' 'category'
demo('subtopic', 'category')
Description
demo displays the list of MATLAB demos in the Help browser.
demo 'subtopic' 'category' displays the list of demos in the product or topic specified by category, where category belongs to subtopic. Allowable values for subtopic are: matlab, toolbox, simulink, and blockset. When subtopic is matlab or simulink, allowable values for categoryare the names of groups demos in those products. To specify all demos for the product when subtopic is matlab or simulink, do not specify category. When subtopic is toolbox, or blockset allowable values for category are products within the specified subtopic. For category, the product name is the toolbox folder for the product. To view the installed toolbox folders, run (fullfile(matlabroot, 'toolbox'))
demo('subtopic', 'category') is the function form of the syntax.
Examples
Display MATLAB demos that are in the Graphics category:
demo 'matlab' 'graphics'

Display all MATLAB demos:
demo 'matlab'
Display demos for the Simulink product, in the Automotive category:
demo 'simulink' 'automotive'
Display demos for the Communications System Toolbox™ product:
demo 'toolbox' 'communications'
Display demos for the Simulink® Control Design™ product:
demo 'simulink' 'simulink control design'


det -Matrix determinant
Syntax
d = det(X)
Description
d = det(X) returns the determinant of the square matrix X.
Tips
Testing singularity using abs(det(X)) <= tolerance is not recommended as it is difficult to choose the correct tolerance. The function cond(X) can check for singular and nearly singular matrices. Algorithms The determinant is computed from the triangular factors obtained by Gaussian elimination [L,U] = lu(A) s = det(L) % This is always +1 or -1 det(A) = s*prod(diag(U)) Examples The statement A = [1 2 3; 4 5 6; 7 8 9] produces A = 1 2 3 4 5 6 7 8 9 This happens to be a singular matrix, so det(A) produces a very small number. Changing A(3,3) with A(3,3) = 0 turns A into a nonsingular matrix. Now d = det(A) produces d = 27. diag -Diagonal matrices and diagonals of matrix Syntax X = diag(v,k) X = diag(v) v = diag(X,k) v = diag(X) Description X = diag(v,k) when v is a vector of n components, returns a square matrix X of order n+abs(k), with the elements of v on the kth diagonal. k = 0represents the main diagonal, k > 0 above the main diagonal, and k < 0 below the main diagonal. X = diag(v) puts v on the main diagonal, same as above with k = 0. v = diag(X,k) for matrix X, returns a column vector v formed from the elements of the kth diagonal of X. v = diag(X) returns the main diagonal of X, same as above with k = 0 . Tips diag(diag(X)) is a diagonal matrix. sum(diag(X)) is the trace of X. diag([]) generates an empty matrix, ([]). diag(m-by-1,k) generates a matrix of size m+abs(k)-by-m+abs(k). diag(1-by-n,k) generates a matrix of size n+abs(k)-by-n+abs(k). Examples The statement diag(-m:m)+diag(ones(2*m,1),1)+diag(ones(2*m,1),-1) produces a tridiagonal matrix of order 2*m+1. dir -List folder contents Syntax dir dir name listing = dir(name) Description dir lists the files and folders in the MATLAB current folder. Results appear in the order returned by the operating system. dir name lists the files and folders that match the string name. When name is a folder, dir lists the contents of the folder. Specify name using absolute or relative path names. You can use wildcards (*). listing = dir(name) returns attributes about name. Tips  To obtain a list of available drives on Microsoft Windows platforms: Use the DOS net use command in the Command Window: dos('net use') Or [s,r] = dos('net use') MATLAB returns the results to the character array r.  Short DOS file name support The MATLAB dir function is consistent with the Microsoft Windows operating system dir command in that both support short file names generated by DOS.  Structure Results for Nonexistent Files When you run dir with an output argument and the results include a nonexistent file or a file that dir cannot query for some other reason, then dirreturns the following default values: date: '' bytes: [] isdir: 0 datenum: [] The most common occurrence is on UNIX[1] platforms when dir queries a file that is a symbolic link, which points to a nonexistent target. A nonexistent target is a target that was moved, removed, or renamed. For example, if my_file in my_dir is a symbolic link to another file that was deleted, then running r = dir('my_dir') includes this result for my_file: r(n) = name: 'my_file' date: '' bytes: [] isdir: 0 datenum: [] where n is the index for my_file, found by searching r by the name field. Input Arguments name A string value specifying a file or folder name. Output Arguments listing Field Name Description Class name File or folder name char array date Modification date timestamp char array bytes Size of the file in bytes double isdir 1 if name is a folder; 0 if not logical datenum Modification date as serial date number. The value is locale-dependent. double Examples View the Contents of a Folder View the contents of the matlab/audiovideo folder: dir(fullfile(matlabroot, 'toolbox/matlab/audiovideo')) Find Information in the Return Structure Return the folder listing, restricted to files with a .m extension, to the variable av_files: av_files = dir(fullfile(matlabroot, ... 'toolbox/matlab/audiovideo/*.m')) MATLAB returns the information in a structure array: av_files = 25x1 struct array with fields: name date bytes isdir datenum Index into the structure to access a particular item: av_files(3).name ans = audioplayerreg.m – Use the Wildcard Character to Find Multiple Files View the MAT-files in the current folder that include the term my_data by using the wildcard character: dir *my_data*.mat MATLAB returns all file names that match this specification. For instance, it returns the following if they are in the current folder: old_my_data.mat my_data_final.mat my_data_test.mat – Exclude Certain Files from the Output Return the list of files in the current folder, excluding those files that dir cannot query: y = dir; y = y(find(~cellfun(@isempty,{y(:).date}))); – Find the Date a File Was Modified To get the serial date number for the date and time a file was last modified, use the datenum field of the structure returned by the dir command: DirInfo = dir('startup.m'); filedate = DirInfo.datenum Using the datenum function to convert the string returned in the date field of the structure is not recommended as this can behave differently in different locales. filedate = datenum(DirInfo.date) Alternatives Use the Current Folder browser to view the list of files in a folder. disp -Display text or array Syntax disp(X) Description disp(X) displays an array, without printing the array name. If X contains a text string, the string is displayed. Another way to display an array on the screen is to type its name, but this prints a leading "X=," which is not always desirable. The disp function accepts only one input. To display more than one array or string, you can use concatenation or the sprintf or fprintf functions as shown in Example 3 — Display multiple items on the same line. Note that disp does not display empty arrays. Examples Example 1 — Display a matrix with column labels This example uses disp to display a matrix with column labels: disp(' Corn Oats Hay') x = gallery('uniformdata',[5 3],0); disp(x) This results in Corn Oats Hay 0.9501 0.7621 0.6154 0.2311 0.4565 0.7919 0.6068 0.0185 0.9218 0.4860 0.8214 0.7382 0.8913 0.4447 0.1763 Example 2 — Display a hyperlink in the Command Window You also can use the disp command to display a hyperlink in the Command Window. Include the full hypertext string on a single line as input to disp: disp('MathWorks Web Site')
which generates this hyperlink in the Command Window:
MathWorks Web Site
Click the link to display the MathWorks home page in a MATLAB Web browser.
Example 3 — Display multiple items on the same line
Use any of the following techniques to display multiple items on the same line:
 Concatenate all substrings together using the [] operator. Convert any numeric values to characters using the num2str function:
 name = 'Alice'; age = 12;
 str = [name, ' will be ', num2str(age), ' this year.']

Alice will be 12 this year.
 Use sprintf to create the string, and disp to display it. Terminate the sprintf command with a semicolon. This keeps "str = " from being displayed:
 name = 'Alice'; age = 12;
 str = sprintf('%s will be %d this year.', name, age);
 disp(str);

Alice will be 12 this year.
 Use fprintf to create and display the string. Unlike the sprintf function, fprintf does not display the "str = " text. However, you do need to end the string with the newline (\n) metacharacter to terminate its display properly:
 name = 'Alice'; age = 12;
 str = fprintf('%s will be %d this year.\n', name, age);

Alice will be 12 this year.


eig -Eigenvalues and eigenvectors
Syntax
d = eig(A)
d = eig(A,B)
[V,D] = eig(A)
[V,D] = eig(A,'nobalance')
[V,D] = eig(A,B)
[V,D] = eig(A,B,flag)
Description
d = eig(A) returns a vector of the eigenvalues of matrix A.
d = eig(A,B) returns a vector containing the generalized eigenvalues, if A and B are square matrices.
Note If S is sparse and symmetric, you can use d = eig(S) to return the eigenvalues of S. If S is sparse but not symmetric, or if you want to return the eigenvectors of S, use the function eigs instead of eig.

[V,D] = eig(A) produces matrices of eigenvalues (D) and eigenvectors (V) of matrix A, so that A*V = V*D. Matrix D is the canonical form of A — a diagonal matrix with A's eigenvalues on the main diagonal. Matrix V is the modal matrix — its columns are the eigenvectors of A.
If W is a matrix such that W'*A = D*W', the columns of W are the left eigenvectors of A. Use [W,D] = eig(A.'); W = conj(W) to compute the left eigenvectors.
[V,D] = eig(A,'nobalance') finds eigenvalues and eigenvectors without a preliminary balancing step. This may give more accurate results for certain problems with unusual scaling. Ordinarily, balancing improves the conditioning of the input matrix, enabling more accurate computation of the eigenvectors and eigenvalues. However, if a matrix contains small elements that are really due to roundoff error, balancing may scale them up to make them as significant as the other elements of the original matrix, leading to incorrect eigenvectors. Use the nobalance option in this event. See thebalance function for more details.
[V,D] = eig(A,B) produces a diagonal matrix D of generalized eigenvalues and a full matrix V whose columns are the corresponding eigenvectors so that A*V = B*V*D .
[V,D] = eig(A,B,flag) specifies the algorithm used to compute eigenvalues and eigenvectors. flag can be:
'chol' Computes the generalized eigenvalues of A and B using the Cholesky factorization of B. This is the default for symmetric (Hermitian) A and symmetric (Hermitian) positive definite B.
'qz' Ignores the symmetry, if any, and uses the QZ algorithm as it would for nonsymmetric (non-Hermitian) Aand B.
Note For eig(A), the eigenvectors are scaled so that the norm of each is 1.0. For eig(A,B), eig(A,'nobalance'), and eig(A,B,flag), the eigenvectors are not normalized.
Also note that if A is symmetric, eig(A,'nobalance') ignores the nobalance option since A is already balanced.
Tips
The eigenvalue problem is to determine the nontrivial solutions of the equation Ax = λx
where A is an n-by-n matrix, x is a length n column vector, and λ is a scalar. The n values of λ that satisfy the equation are the eigenvalues, and the corresponding values of x are the right eigenvectors. TheMATLAB function eig solves for the eigenvalues λ, and optionally the eigenvectors x.
The generalized eigenvalue problem is to determine the nontrivial solutions of the equation Ax = λBx
where both A and B are n-by-n matrices and λ is a scalar. The values of λ that satisfy the equation are the generalized eigenvalues and the corresponding values of are the generalized right eigenvectors.
If B is nonsingular, the problem could be solved by reducing it to a standard eigenvalue problem B–1Ax = λx
Because B can be singular, an alternative algorithm, called the QZ method, is necessary.
When a matrix has no repeated eigenvalues, the eigenvectors are always independent and the eigenvector matrix V diagonalizes the original matrix A if applied as a similarity transformation. However, if a matrix has repeated eigenvalues, it is not similar to a diagonal matrix unless it has a full (independent) set of eigenvectors. If the eigenvectors are not independent then the original matrix is said to be defective. Even if a matrix is defective, the solution from eig satisfies A*X = X*D.
Examples
The matrix
B = [ 3 -2 -.9 2*eps
-2 4 1 -eps
-eps/4 eps/2 -1 0
-.5 -.5 .1 1 ];
has elements on the order of roundoff error. It is an example for which the nobalance option is necessary to compute the eigenvectors correctly. Try the statements
[VB,DB] = eig(B)
B*VB - VB*DB
[VN,DN] = eig(B,'nobalance')
B*VN - VN*DN


error -Display message and abort function
Syntax
error('msgIdent', 'msgString', v1, v2, ..., vN)
error('msgString', v1, v2, ...)
error('msgString')
error(msgStruct)
Description
error('msgIdent', 'msgString', v1, v2, ..., vN) generates an exception if the currently-running function tests for and confirms a faulty or unexpected condition. Depending on how the program has been designed to respond to the error, MATLAB either enters a catch block to handle the error condition, or exits the program.
The msgIdent argument is a unique message identifier string that MATLAB attaches to the error message when it throws the error. A message identifier has the format component:mnemonic. Its purpose is to better identify the source of the error (see Message Identifiers in the MATLAB Programming Fundamentals documentation for more information).
The msgString argument is a character string that informs the user about the cause of the error and can also suggest how to correct the faulty condition. The msgString string can include escape sequences such as \t or \n, as well as any of the format specifiers supported by the sprintffunction (such as %s or %d). Additional arguments v1, v2, ..., vN provide values that correspond to and replace the conversion specifiers.
For example, if msgString is "Error on line %d, command %s", then v1 is the line number at which the error was detected, and v2 is the command that failed. See Formatting Strings in the MATLAB Programming Fundamentals documentation for more detailed information on using string formatting commands.
All string input arguments must be enclosed in single quotation marks. If msgString is an empty string, the error command has no effect.
error('msgString', v1, v2, ...)reports an error without including a message identifier in the error report. Although including a message identifier in an error report is recommended, it is not required.
error('msgString') is the same as the above syntax, except that the msgString string contains no conversion specifiers, no escape sequences, and no substitution value (v1, v2, ...) arguments. All characters in msgString are interpreted exactly as they appear in the msgString argument. MATLAB displays the \t in 'C:\testFolder' for example, as a backslash character followed by the letter t, and not as a horizontal tab.
error(msgStruct) accepts a scalar error structure input msgStruct with at least one of the fields message, identifier, and stack. When themsgStruct input includes a stack field, the stack field of the error will be set according to the contents of the stack input. When specifying a stackinput, use the absolute file name and the entire sequence of functions that nests the function in the stack frame. This is the same as the string returned by dbstack('-completenames'). If msgStruct is an empty structure, no action is taken and error returns without exiting the function.
Tips
The error function captures what information it can about the error that occurred and stores it in a data structure that is an object of the MExceptionclass. This error record contains the error message string, message identifier, the error stack, and optionally an array of other exception objects that are intended to provide information as to the cause of the exception. See Capturing Information About the Error for more information on how to access and use an exception object.
You can access information in the exception object using the catch function as documented in the catch reference page. If your program terminates because of an exception and returns control to the Command Prompt, you can access the exception object using the MException.last command.
The error function also determines where the error occurred and provides this information in the stack field of the MException object. This field contains a structure array that has the same format as the output of the dbstack function. This stack points to the line where the error function was called.
The following table shows the MATLAB functions that can be useful for throwing an exception:
Function Description
error Throw exception with specified error message.
assert Evaluate given expression and throw exception if false.
throw Throw exception based on specified MException object.
throwAsCaller Throw exception that appears to have been thrown by the calling function.
rethrow Reissue previously caught exception.
Examples
Example 1 — Simple Error Message
Write a short function errtest1 that throws an error when called with an incorrect number of input arguments. Include a message identifier'myApp:argChk' and error message:
function errtest1(x, y)
if nargin ~= 2
error('myApp:argChk', 'Wrong number of input arguments')
end
Call the function with an incorrect number of inputs. The call to nargin, a function that checks the number of inputs, fails and the program calls error:
errtest1(pi)

Error using errtest1 (line 3)
Wrong number of input arguments
If you run this function from the Command Window, you can use the MException.last method to view the exception object:
err = MException.last
err =
MException

Properties:
identifier: 'myApp:argChk'
message: 'Wrong number of input arguments'
cause: {}
stack: [1x1 struct]
Methods
err.stack
ans =
file: 'c:\work\errtest1.m'
name: 'errtest1'
line: 3
Example 2 — Special Characters
MATLAB converts special characters (like \n and %d) in the error message string only when you specify more than one input argument with error. In the single-argument case shown below, \n is taken to mean backslash-n. It is not converted to a newline character:
error('In this case, the newline \n is not converted.')

In this case, the newline \n is not converted.
But, when more than one argument is specified, MATLAB does convert special characters. This holds true regardless of whether the additional argument supplies conversion values or is a message identifier:
error('ErrorTests:convertTest', ...
'In this case, the newline \n is converted.')

In this case, the newline
is converted.

errorbar -Plot error bars along curve

Alternatives
To graph selected variables, use the Plot Selector in the Workspace Browser, or use the Figure Palette Plot Catalog. Manipulate graphs in plot edit mode with the Property Editor. For details, see "Plotting Tools — Interactive Plotting" in the MATLAB Graphics documentation and"Creating Graphics from the Workspace Browser" in the MATLAB Desktop Tools documentation.
Syntax
errorbar(Y,E)
errorbar(X,Y,E)
errorbar(X,Y,L,U)
errorbar(...,LineSpec)
h = errorbar(...)
Description
Error bars show the confidence intervals of data or the deviation along a curve.
errorbar(Y,E) plots Y and draws an error bar at each element of Y. The error bar is a distance of E(i) above and below the curve so that each bar is symmetric and 2*E(i) long.
errorbar(X,Y,E) plots Y versus X with symmetric error bars 2*E(i) long. X, Y, E must be the same size. When they are vectors, each error bar is a distance of E(i) above and below the point defined by (X(i),Y(i)). When they are matrices, each error bar is a distance of E(i,j) above and below the point defined by (X(i,j),Y(i,j)).
errorbar(X,Y,L,U) plots X versus Y with error bars L(i)+U(i) long specifying the lower and upper error bars. X, Y, L, and U must be the same size. When they are vectors, each error bar is a distance of L(i) below and U(i) above the point defined by (X(i),Y(i)). When they are matrices, each error bar is a distance of L(i,j) below and U(i,j) above the point defined by (X(i,j),Y(i,j)).
errorbar(...,LineSpec) uses the color and line style specified by the string 'LineSpec'. The color is applied to the data line and error bars. The linestyle and marker are applied to the data line only. See linespec for examples of styles.
h = errorbar(...) returns handles to the errorbarseries objects created. errorbar creates one object for vector input arguments and one object per column for matrix input arguments. See errorbarseries properties for more information.
When the arguments are all matrices, errorbar draws one line per matrix column. If X and Y are vectors, they specify one curve.
Examples
Draw symmetric error bars that are two standard deviation units in length:
X = 0:pi/10:pi;
Y = sin(X);
E = std(Y)*ones(size(X));
errorbar(X,Y,E)

Plot the computed average traffic volume and computed standard deviations for three street locations over the course of a day using red 'x' markers:
load count.dat;
y = mean(count,2);
e = std(count,1,2);
figure
errorbar(y,e,'xr')


etime -Time elapsed between date vectors
Syntax
e = etime(t2, t1)
Description
e = etime(t2, t1) returns the number of seconds between vectors t1 and t2. The two vectors must be six elements long, in the format returned byclock:
T = [Year Month Day Hour Minute Second]
Tips
etime does not account for the following:
 Leap seconds.
 Daylight savings time adjustments.
 Differences in time zones.
When timing the duration of an event, use the tic and toc functions instead of clock and etime. clock uses the system time, which might be adjusted periodically by the operating system and thus might not be reliable in time comparison operations.
Examples
This example shows two ways to calculate how long a particular FFT operation takes. Using tic and toc is preferred, as it can be more reliable for timing the duration of an event:
x = rand(800000, 1);

t1 = tic; fft(x); toc(t1) % Recommended
Elapsed time is 0.097665 seconds.

t = clock; fft(x); etime(clock, t)
ans =
0.1250




eval -Execute string containing MATLAB expression
Syntax
eval(expression)
[a1, a2, a3, ...] = eval('myfun(b1, b2, b3, ...)')
Description
eval(expression) executes expression, a string containing any valid MATLAB expression. You can construct expression by concatenating substrings and variables inside square brackets:
expression = [string1, int2str(var), string2, ...]
[a1, a2, a3, ...] = eval('myfun(b1, b2, b3, ...)') executes function myfun with arguments b1, b2, b3, ..., and returns the results in the specified output variables.
Tips
Using the eval output argument list is recommended over including the output arguments in the expression string. The first syntax below avoids strict checking by the MATLAB parser and can produce untrapped errors and other unexpected behavior. Use the second syntax instead:
% Not recommended
eval('[a1, a2, a3, ...] = function(var)')

% Recommended syntax
[a1, a2, a3, ...] = eval('function(var)')
Examples
Example 1 – Working with a Series of Files
Load MAT-files August1.mat to August10.mat into the MATLAB workspace:
for d=1:10
s = ['load August' int2str(d) '.mat']
eval(s)
end
These are the strings being evaluated:
s =
load August1.mat
s =
load August2.mat
s =
load August3.mat
- etc. -
Example 2 – Assigning to Variables with Generated Names
Generate variable names that are unique in the MATLAB workspace and assign a value to each using eval:
for k = 1:5
t = clock;
pause(uint8(rand * 10));
v = genvarname('time_elapsed', who);
eval([v ' = etime(clock,t)'])
end
As this code runs, eval creates a unique statement for each assignment:
time_elapsed =
5.0070
time_elapsed1 =
2.0030
time_elapsed2 =
7.0010
time_elapsed3 =
8.0010
time_elapsed4 =
3.0040
Example 3 – Evaluating a Returned Function Name
The following command removes a figure by evaluating its CloseRequestFcn property as returned by get.
eval(get(h,'CloseRequestFcn'))


exist -Check existence of variable, function, folder, or class
Alternatives
As an alternative to the exist function, use the MATLAB Workspace Browser or the Current Folder browser.
Syntax
exist name
exist name kind
A = exist('name','kind')
Description
exist name returns the status of name:
0 name does not exist.
1 name is a variable in the workspace.
2 One of the following is true:
 name exists on your MATLAB search path as a file with extension .m.
 name is the name of an ordinary file on your MATLAB search path.
 name is the full pathname to any file.
3 name exists as a MEX- or DLL-file on your MATLAB search path.
4 name exists as an MDL-file on your MATLAB search path.
5 name is a built-in MATLAB function.
6 name is a P-file on your MATLAB search path.
7 name is a folder.
8 name is a class. (exist returns 0 for Java classes if you start MATLAB with the -nojvmoption.)
If name is a class, then exist('name') returns an 8. However, if name is a class file, then exist('name') returns a 2.
If a file or folder is not on the search path, then name must specify either a full pathname, a partial pathname relative to MATLABPATH, a partial pathname relative to your current folder, or the file or folder must reside in your current working folder.
If name specifies a filename, that filename may include an extension to preclude conflicting with other similar filenames. For example,exist('file.ext').
exist name kind returns the status of name for the specified kind. If name of type kind does not exist, it returns 0. The kind argument may be one of the following:
builtin Checks only for built-in functions.
class Checks only for classes.
dir Checks only for folders.
file Checks only for files or folders.
var Checks only for variables.
If you do not specify a kind argument, and name belongs to more than one of these categories, exist returns one value according to the order of evaluation shown in the table below. For example, if name matches both a folder and a file that defines a MATLAB function, exist returns 7, identifying it as a folder.
Order of Evaluation Return Value Type of Entity
1 1 Variable
2 5 Built-in
3 7 Folder
4 3 MEX or DLL-file
5 4 MDL-file
6 6 P-file
7 2 MATLAB function
8 8 Class
A = exist('name','kind') is the function form of the syntax.
Tips
If name specifies a filename, MATLAB attempts to locate the file, examines the filename extension, and determines the value to return based on the extension alone. MATLAB does not examine the contents or internal structure of the file.
You can specify a partial path to a folder or file. A partial pathname is a pathname relative to the MATLAB path that contains only the trailing one or more components of the full pathname. For example, both of the following commands return 2, identifying mkdir.m as a MATLAB function. The first uses a partial pathname:
exist('matlab/general/mkdir.m')
exist([matlabroot '/toolbox/matlab/general/mkdir.m'])
To check for the existence of more than one variable, use the ismember function. For example,
a = 5.83;
c = 'teststring';
ismember({'a','b','c'},who)

ans =

1 0 1
Examples
This example uses exist to check whether a MATLAB function is a built-in function or a file:
type = exist('plot')
type =
5
This indicates that plot is a built-in function.
Run exist on a class folder and then on the constructor within that folder:
exist('@portfolio')
ans =
7 % @portfolio is a folder

exist('@portfolio\portfolio')
ans =
2 % portfolio is a MATLAB function
The following example indicates that testresults is both a variable in the workspace and a folder on the search path:
exist('testresults','var')
ans =
1
exist('testresults','dir')
ans = 7



exp -Exponential
Syntax
Y = exp(X)
Description
Y = exp(X) returns the exponential for each element of X. exp operates element-wise on arrays. For complex x + i * y, exp returns the complex exponential ez = ex(cos y + i sin y). Use expm for matrix exponentials.
Examples
Find the value of eiπ:
y=exp(i*pi)
returns
y =

-1.0000 + 0.0000i


eye -Identity matrix
Syntax
Y = eye(n)
Y = eye(m,n)
Y = eye([m n])
Y = eye(size(A))
Y = eye
Y = eye(m, n, classname)
Description
Y = eye(n) returns the n-by-n identity matrix.
Y = eye(m,n) or Y = eye([m n]) returns an m-by-n matrix with 1's on the diagonal and 0's elsewhere. The size inputs m and n should be nonnegative integers. Negative integers are treated as 0.
Y = eye(size(A)) returns an identity matrix the same size as A.
Y = eye with no arguments is the scalar 1.
Y = eye(m, n, classname) is an m-by-n matrix with 1's of class classname on the diagonal and zeros of class classname elsewhere. classname is a string specifying the data type of the output. classname can take the following values: 'double', 'single', 'int8', 'uint8', 'int16', 'uint16','int32', 'uint32', 'int64', or 'uint64'.
The identity matrix is not defined for higher-dimensional arrays. The assignment y = eye([2,3,4]) results in an error.
Examples
Return a 2-by-3 matrix of class int8:
x = eye(2,3,'int8');


find -Find indices and values of nonzero elements
Syntax
ind = find(X)
ind = find(X, k)
ind = find(X, k, 'first')
ind = find(X, k, 'last')
[row,col] = find(X, ...)
[row,col,v] = find(X, ...)
Description
ind = find(X) locates all nonzero elements of array X, and returns the linear indices of those elements in vector ind. If X is a row vector, then ind is a row vector; otherwise, ind is a column vector. If X contains no nonzero elements or is an empty array, then ind is an empty array.
ind = find(X, k) or ind = find(X, k, 'first') returns at most the first k indices corresponding to the nonzero entries of X. k must be a positive integer, but it can be of any numeric data type.
ind = find(X, k, 'last') returns at most the last k indices corresponding to the nonzero entries of X.
[row,col] = find(X, ...) returns the row and column indices of the nonzero entries in the matrix X. This syntax is especially useful when working with sparse matrices. If X is an N-dimensional array with N > 2, col contains linear indices for the columns. For example, for a 5-by-7-by-3 array X with a nonzero element at X(4,2,3), find returns 4 in row and 16 in col. That is, (7 columns in page 1) + (7 columns in page 2) + (2 columns in page 3) = 16.
[row,col,v] = find(X, ...) returns a column or row vector v of the nonzero entries in X, as well as row and column indices. If X is a logical expression, then v is a logical array. Output v contains the non-zero elements of the logical array obtained by evaluating the expression X. For example,
A= magic(4)
A =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1

[r,c,v]= find(A>10);

r', c', v'
ans =
1 2 4 4 1 3
ans =
1 2 2 3 4 4
ans =
1 1 1 1 1 1
Here the returned vector v is a logical array that contains the nonzero elements of N where
N=(A>10)
Examples
Example 1
X = [1 0 4 -3 0 0 0 8 6];
indices = find(X)
returns linear indices for the nonzero entries of X.
indices =
1 3 4 8 9
Example 2
You can use a logical expression to define X. For example,
find(X > 2)
returns linear indices corresponding to the entries of X that are greater than 2.
ans =
3 8 9
Example 3
The following find command
X = [3 2 0; -5 0 7; 0 0 1];
[r,c,v] = find(X)
returns a vector of row indices of the nonzero entries of X
r =
1
2
1
2
3
a vector of column indices of the nonzero entries of X
c =
1
1
2
3
3
and a vector containing the nonzero entries of X.
v =
3
-5
2
7
1
Example 4
The expression
X = [3 2 0; -5 0 7; 0 0 1];
[r,c,v] = find(X>2)
returns a vector of row indices of the nonzero entries of N where N=(X>2)
r =
1
2
a vector of column indices of the nonzero entries of N where N=(X>2)
c =
1
3
and a logical array that contains the nonzero elements of N where N=(X>2).
v =
1
1
Recall that when you use find on a logical expression, the output vector v does not contain the nonzero entries of the input array. Instead, it contains the nonzero values returned after evaluating the logical expression.
Example 5
Some operations on a vector
x = [11 0 33 0 55]';

find(x)
ans =
1
3
5

find(x == 0)
ans =
2
4

find(0 < x & x < 10*pi) ans = 1 Example 6 For the matrix M = magic(3) M = 8 1 6 3 5 7 4 9 2 find(M > 3, 4)
returns the indices of the first four entries of M that are greater than 3.
ans =
1
3
5
6
Example 7
If X is a vector of all zeros, find(X) returns an empty matrix. For example,
indices = find([0;0;0])
indices =
Empty matrix: 0-by-1
fix -Round toward zero
Syntax
B = fix(A)
Description
B = fix(A) rounds the elements of A toward zero, resulting in an array of integers. For complex A, the imaginary and real parts are rounded independently.
Examples
a = [-1.9, -0.2, 3.4, 5.6, 7.0, 2.4+3.6i]

a =
Columns 1 through 4
-1.9000 -0.2000 3.4000 5.6000

Columns 5 through 6
7.0000 2.4000 + 3.6000i

fix(a)

ans =
Columns 1 through 4
-1.0000 0 3.0000 5.0000

Columns 5 through 6
7.0000 2.0000 + 3.0000i
fliplr -Flip matrix left to right
Description
Refer to the MATLAB fliplr reference page for more information.


flipud -Flip matrix up to down
Syntax
B = flipud(A)
Description
B = flipud(A) returns A with rows flipped in the up-down direction, that is, about a horizontal axis.
If A is a column vector, then flipud(A) returns a vector of the same length with the order of its elements reversed. If A is a row vector, then flipud(A)simply returns A.
Examples
If A is the 3-by-2 matrix,
A =
1 4
2 5
3 6
then flipud(A) produces
3 6
2 5
1 4
If A is a column vector,
A =
3
5
7
then flipud(A) produces
A =
7
5
3
Limitations
The array being operated on cannot have more than two dimensions. This limitation exists because the axis upon which to flip a multidimensional array would be undefined.


floor -Round toward negative infinity
Syntax
B = floor(A)
Description
B = floor(A) rounds the elements of A to the nearest integers less than or equal to A. For complex A, the imaginary and real parts are rounded independently.
Examples
a = [-1.9, -0.2, 3.4, 5.6, 7.0, 2.4+3.6i]

a =
Columns 1 through 4
-1.9000 -0.2000 3.4000 5.6000

Columns 5 through 6
7.0000 2.4000 + 3.6000i

floor(a)

ans =
Columns 1 through 4
-2.0000 -1.0000 3.0000 5.0000

Columns 5 through 6
7.0000 2.0000 + 3.0000i


fminbnd -Find minimum of single-variable function on fixed interval
Syntax
x = fminbnd(fun,x1,x2)
x = fminbnd(fun,x1,x2,options)
[x,fval] = fminbnd(...)
[x,fval,exitflag] = fminbnd(...)
[x,fval,exitflag,output] = fminbnd(...)
Description
fminbnd finds the minimum of a function of one variable within a fixed interval.
x = fminbnd(fun,x1,x2) returns a value x that is a local minimizer of the function that is described in fun in the interval x1 < x < x2. fun is a function handle. See Function Handles in the MATLAB Programming documentation for more information. Parameterizing Functions in the MATLAB Mathematics documentation, explains how to pass additional parameters to your objective function fun. x = fminbnd(fun,x1,x2,options) minimizes with the optimization parameters specified in the structure options. You can define these parameters using the optimset function. fminbnd uses these options structure fields: Display Level of display. 'off' displays no output; 'iter' displays output at each iteration; 'final' displays just the final output; 'notify' (default) displays output only if the function does not converge. See Iterative Display in MATLAB Mathematics for more information. FunValCheck Check whether objective function values are valid. 'on' displays an error when the objective function returns a value that is complex or NaN. 'off' displays no error. MaxFunEvals Maximum number of function evaluations allowed. MaxIter Maximum number of iterations allowed. OutputFcn User-defined function that is called at each iteration. See Output Functions in MATLAB Mathematics for more information. PlotFcns Plots various measures of progress while the algorithm executes, select from predefined plots or write your own. Pass a function handle or a cell array of function handles. The default is none ([]).  @optimplotx plots the current point  @optimplotfval plots the function value  @optimplotfunccount plots the function count See Plot Functions in MATLAB Mathematics for more information. TolX Termination tolerance on x. [x,fval] = fminbnd(...) returns the value of the objective function computed in fun at x. [x,fval,exitflag] = fminbnd(...) returns a value exitflag that describes the exit condition of fminbnd: 1 fminbnd converged to a solution x based on options.TolX. 0 Maximum number of function evaluations or iterations was reached. -1 Algorithm was terminated by the output function. -2 Bounds are inconsistent (x1 > x2).
[x,fval,exitflag,output] = fminbnd(...) returns a structure output that contains information about the optimization in the following fields:
algorithm Algorithm used
funcCount Number of function evaluations
iterations Number of iterations
message Exit message
Arguments
fun is the function to be minimized. fun accepts a scalar x and returns a scalar f, the objective function evaluated at x. The function fun can be specified as a function handle for a function file
x = fminbnd(@myfun,x1,x2);
where myfun.m is a function file such as
function f = myfun(x)
f = ... % Compute function value at x.
or as a function handle for an anonymous function:
x = fminbnd(@(x) sin(x*x),x1,x2);
Other arguments are described in the syntax descriptions above.
Examples
x = fminbnd(@cos,3,4) computes π to a few decimal places and gives a message on termination.
[x,fval,exitflag] = ...
fminbnd(@cos,3,4,optimset('TolX',1e-12,'Display','off'))
computes π to about 12 decimal places, suppresses output, returns the function value at x, and returns an exitflag of 1.
The argument fun can also be a function handle for an anonymous function. For example, to find the minimum of the function f(x) = x3 – 2x – 5 on the interval (0,2), create an anonymous function f
f = @(x)x.^3-2*x-5;
Then invoke fminbnd with
x = fminbnd(f, 0, 2)
The result is
x =
0.8165
The value of the function at the minimum is
y = f(x)

y =
-6.0887
If fun is parameterized, you can use anonymous functions to capture the problem-dependent parameters. For example, suppose you want to minimize the objective function myfun defined by the following function file:
function f = myfun(x,a)
f = (x - a)^2;
Note that myfun has an extra parameter a, so you cannot pass it directly to fminbind. To optimize for a specific value of a, such as a = 1.5.
1. Assign the value to a.
a = 1.5; % define parameter first
2. Call fminbnd with a one-argument anonymous function that captures that value of a and calls myfun with two arguments:
x = fminbnd(@(x) myfun(x,a),0,1)
Algorithms
fminbnd is a function file. Its algorithm is based on golden section search and parabolic interpolation. Unless the left endpoint x1 is very close to the right endpoint x2, fminbnd never evaluates fun at the endpoints, so fun need only be defined for x in the interval x1 < x < x2. If the minimum actually occurs at x1 or x2, fminbnd returns an interior point at a distance of no more than 2*TolX from x1 or x2, where TolX is the termination tolerance. See [1] or [2]for details about the algorithm. Limitations The function to be minimized must be continuous. fminbnd may only give local solutions. fminbnd often exhibits slow convergence when the solution is on a boundary of the interval. fminbnd only handles real variables. fminsearch -Find minimum of unconstrained multivariable function using derivative-free method Syntax x = fminsearch(fun,x0) x = fminsearch(fun,x0,options) [x,fval] = fminsearch(...) [x,fval,exitflag] = fminsearch(...) [x,fval,exitflag,output] = fminsearch(...) Description fminsearch finds the minimum of a scalar function of several variables, starting at an initial estimate. This is generally referred to as unconstrained nonlinear optimization. x = fminsearch(fun,x0) starts at the point x0 and returns a value x that is a local minimizer of the function described in fun. x0 can be a scalar, vector, or matrix. fun is a function handle. See Function Handles in the MATLAB Programming documentation for more information. Parameterizing Functions in the MATLAB Mathematics documentation explains how to pass additional parameters to your objective function fun. See alsoExample 2 and Example 3 below. x = fminsearch(fun,x0,options) minimizes with the optimization parameters specified in the structure options. You can define these parameters using the optimset function. fminsearch uses these options structure fields: Display Level of display. 'off' displays no output; 'iter' displays output at each iteration; 'final' displays just the final output; 'notify' (default) displays output only if the function does not converge. See Iterative Displayin MATLAB Mathematics for more information. FunValCheck Check whether objective function values are valid. 'on' displays an error when the objective function returns a value that is complex, Inf or NaN. 'off' (the default) displays no error. MaxFunEvals Maximum number of function evaluations allowed MaxIter Maximum number of iterations allowed OutputFcn User-defined function that is called at each iteration. See Output Functions in MATLAB Mathematics for more information. PlotFcns Plots various measures of progress while the algorithm executes, select from predefined plots or write your own. Pass a function handle or a cell array of function handles. The default is none ([]).  @optimplotx plots the current point  @optimplotfval plots the function value  @optimplotfunccount plots the function count See Plot Functions in MATLAB Mathematics for more information. TolFun Termination tolerance on the function value TolX Termination tolerance on x [x,fval] = fminsearch(...) returns in fval the value of the objective function fun at the solution x. [x,fval,exitflag] = fminsearch(...) returns a value exitflag that describes the exit condition of fminsearch: 1 fminsearch converged to a solution x. 0 Maximum number of function evaluations or iterations was reached. -1 Algorithm was terminated by the output function. [x,fval,exitflag,output] = fminsearch(...) returns a structure output that contains information about the optimization in the following fields: algorithm 'Nelder-Mead simplex direct search' funcCount Number of function evaluations iterations Number of iterations message Exit message Arguments fun is the function to be minimized. It accepts an input x and returns a scalar f, the objective function evaluated at x. The function fun can be specified as a function handle for a function file x = fminsearch(@myfun, x0) where myfun is a function file such as function f = myfun(x) f = ... % Compute function value at x or as a function handle for an anonymous function, such as x = fminsearch(@(x)sin(x^2), x0); Other arguments are described in the syntax descriptions above. Examples Example 1 The Rosenbrock banana function is a classic test example for multidimensional minimization: The minimum is at (1,1) and has the value 0. The traditional starting point is (-1.2,1). The anonymous function shown here defines the function and returns a function handle called banana: banana = @(x)100*(x(2)-x(1)^2)^2+(1-x(1))^2; Pass the function handle to fminsearch: [x,fval] = fminsearch(banana,[-1.2, 1]) This produces x = 1.0000 1.0000 fval = 8.1777e-010 This indicates that the minimizer was found to at least four decimal places with a value near zero. Example 2 If fun is parameterized, you can use anonymous functions to capture the problem-dependent parameters. For example, suppose you want to minimize the objective function myfun defined by the following function file: function f = myfun(x,a) f = x(1)^2 + a*x(2)^2; Note that myfun has an extra parameter a, so you cannot pass it directly to fminsearch. To optimize for a specific value of a, such as a = 1.5. 1. Assign the value to a. a = 1.5; % define parameter first 2. Call fminsearch with a one-argument anonymous function that captures that value of a and calls myfun with two arguments: x = fminsearch(@(x) myfun(x,a),[0,1]) Example 3 You can modify the first example by adding a parameter a to the second term of the banana function: This changes the location of the minimum to the point [a,a^2]. To minimize this function for a specific value of a, for example a = sqrt(2), create a one-argument anonymous function that captures the value of a. a = sqrt(2); banana = @(x)100*(x(2)-x(1)^2)^2+(a-x(1))^2; Then the statement [x,fval] = fminsearch(banana, [-1.2, 1], ... optimset('TolX',1e-8)); seeks the minimum [sqrt(2), 2] to an accuracy higher than the default on x. Algorithms fminsearch uses the simplex search method of Lagarias et al. [1]. This is a direct search method that does not use numerical or analytic gradients. If n is the length of x, a simplex in n-dimensional space is characterized by the n+1 distinct vectors that are its vertices. In two-space, a simplex is a triangle; in three-space, it is a pyramid. At each step of the search, a new point in or near the current simplex is generated. The function value at the new point is compared with the function's values at the vertices of the simplex and, usually, one of the vertices is replaced by the new point, giving a new simplex. This step is repeated until the diameter of the simplex is less than the specified tolerance. For more information, see fminsearch Algorithm. Limitations fminsearch can often handle discontinuity, particularly if it does not occur near the solution. fminsearch may only give local solutions. fminsearch only minimizes over the real numbers, that is, x must only consist of real numbers and f(x) must only return real numbers. When x has complex variables, they must be split into real and imaginary parts. for -Execute statements specified number of times Syntax for index = values program statements : end Description 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 increments index by the value step on each iteration, or decrements when step is negative. 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 ntimes, where n is the number of columns of valArray, given by numel(valArray, 1, :). The inputvalArray can be of any MATLAB data type, including a string, cell array, or struct. Tips  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.  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); % Preallocate matrix 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 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 fprintf -Write data to text file Syntax fprintf(fileID, format, A, ...) fprintf(format, A, ...) count = fprintf(...) Description fprintf(fileID, format, A, ...) applies the format to all elements of array A and any additional array arguments in column order, and writes the data to a text file. fprintf uses the encoding scheme specified in the call to fopen. fprintf(format, A, ...) formats data and displays the results on the screen. count = fprintf(...) returns the number of bytes that fprintf writes. Input Arguments fileID One of the following:  An integer file identifier obtained from fopen.  1 for standard output (the screen).  2 for standard error. Default: 1 (the screen) format String in single quotation marks that describes the format of the output fields. Can include combinations of the following:  Percent sign followed by a conversion character, such as '%s' for strings.  Operators that describe field width, precision, and other options.  Literal text to print.  Escape characters, including: '' Single quotation mark %% Percent character \\ Backslash \a Alarm \b Backspace \f Form feed \n New line \r Carriage return \t Horizontal tab \v Vertical tab \xN Hexadecimal number, N \N Octal number, N Conversion characters and optional operators appear in the following order (includes spaces for clarity): The following table lists the available conversion characters and subtypes. Value Type Conversion Details Integer, signed %d or %i Base 10 Integer, unsigned %u Base 10 %o Base 8 (octal) %x Base 16 (hexadecimal), lowercase letters a–f %X Same as %x, uppercase letters A–F Floating-point number %f Fixed-point notation %e Exponential notation, such as 3.141593e+00 %E Same as %e, but uppercase, such as 3.141593E+00 %g The more compact of %e or %f, with no trailing zeros %G The more compact of %E or %f, with no trailing zeros %bx or %bX %bo %bu Double-precision hexadecimal, octal, or decimal value Example: %bx prints pi as 400921fb54442d18 %tx or %tX %to %tu Single-precision hexadecimal, octal, or decimal value Example: %tx prints pi as 40490fdb Characters %c Single character %s String of characters Additional operators include:  Field width Minimum number of characters to print. Can be a number, or an asterisk (*) to refer to an argument in the input list. For example, the input list ('%12d', intmax) is equivalent to ('%*d', 12, intmax).  Precision For %f, %e, or %E: Number of digits to the right of the decimal point. Example: '%6.4f' prints pi as '3.1416' For %g or %G Number of significant digits. Example: '%6.4g' prints pi as ' 3.142'  Can be a number, or an asterisk (*) to refer to an argument in the input list. For example, the input list ('%6.4f', pi)is equivalent to ('%*.*f', 6, 4, pi).  Flags Action Flag Example Left-justify. '–' %-5.2f Print sign character (+ or –). '+' %+5.2f Insert a space before the value. ' ' % 5.2f Pad with zeros. '0' %05.2f Modify selected numeric conversions:  For %o, %x, or %X, print 0, 0x, or 0X prefix.  For %f, %e, or %E, print decimal point even when precision is 0.  For %g or %G, do not remove trailing zeros or decimal point. '#' %#5.0f  Identifier Order for processing inputs. Use the syntax n$, where n represents the position of the value in the input list. For example, '%3$s %2$s %1$s %2$s' prints inputs 'A', 'B', 'C' as follows: C B A B. The following limitations apply to conversions:  Numeric conversions print only the real component of complex numbers.  If you specify a conversion that does not fit the data, such as a string conversion for a numeric value, MATLAB overrides the specified conversion, and uses %e.  If you apply a string conversion (%s) to integer values, MATLAB converts values that correspond to valid character codes to characters. For example, '%s' converts [65 66 67] to ABC.  Different platforms display exponential notation (such as %e) with a different number of digits in the exponent. Platform Example Windows 1.23e+004 UNIX 1.23e+04  Different platforms display negative zero (-0) differently. Conversion Character Platform %e or %E %f %g or %G Windows 0.000000e+000 0.000000 0 Others -0.000000e+00 -0.000000 -0 A Numeric or character array. Examples Print multiple values and literal text to the screen: B = [8.8 7.7 ; ... 8800 7700]; fprintf('X is %4.2f meters or %8.3f mm\n', 9.9, 9900, B) MATLAB displays: X is 9.90 meters or 9900.000 mm X is 8.80 meters or 8800.000 mm X is 7.70 meters or 7700.000 mm Explicitly convert double-precision values with fractions to integer values, and print to the screen: a = [1.02 3.04 5.06]; fprintf('%d\n', round(a)); Write a short table of the exponential function to a text file called exp.txt: x = 0:.1:1; y = [x; exp(x)]; % open the file with write permission fid = fopen('exp.txt', 'w'); fprintf(fid, '%6.2f %12.8f\n', y); fclose(fid); % view the contents of the file type exp.txt MATLAB import functions, all UNIX applications, and Microsoft Word and WordPad recognize '\n' as a newline indicator. However, if you plan to read the file with Microsoft Notepad, use '\r\n' to move to a new line when writing. For example, replace the previous call to fprintf with the following: fprintf(fid, '%6.2f %12.8f\r\n', y); On a Windows system, convert PC-style exponential notation (three digits in the exponent) to UNIX-style notation (two digits), and print data to a file: a = [0.06 0.1 5 300] % use sprintf to convert the numeric data to text, using %e a_str = sprintf('%e\t',a) % use strrep to replace exponent prefix with shorter version a_str = strrep(a_str,'e+0','e+'); a_str = strrep(a_str,'e-0','e-'); % call fprintf to print the updated text strings fid = fopen('newfile.txt','w'); fprintf(fid, '%s', a_str); fclose(fid); % view the contents of the file type newfile.txt Display a hyperlink (The MathWorks Web Site) on the screen: site = 'http://www.mathworks.com'; title = 'The MathWorks Web Site'; fprintf('%s\n', site, title)
References
[1] Kernighan, B. W., and D. M. Ritchie, The C Programming Language, Second Edition, Prentice-Hall, Inc., 1988.
[2] ANSI specification X3.159-1989: "Programming Language C," ANSI, 1430 Broadway, New York, NY 10018.

function -Declare function
Syntax
function [out1, out2, ...] = myfun(in1, in2, ...)
Description
function [out1, out2, ...] = myfun(in1, in2, ...) declares the function myfun, and its inputs and outputs. The function declaration must be the first executable line of any MATLAB function.
The existing commands and functions that compose the new function reside in a text file that has a .m extension to its filename.
MATLAB program files can be either scripts or functions. Scripts are simply files containing a sequence of MATLAB statements. Functions make use of their own local variables and accept input arguments.
The name of a MATLAB function file begins with an alphabetic character and has a filename extension of .m. The file name, less its extension, is what MATLAB searches for when you try to use the script or function.
The first line of a function defines the syntax with which you call it. The name you give to a function, as defined in the first line, should be the same as the name of the file containing the function, but without the .m extension.
The variables within the body of the function are all local variables.
A subfunction,visible only to the other functions in the same file, is created by defining a new function with the function keyword after the body of the preceding function or subfunction. Subfunctions are not visible outside the file where they are defined.
You can terminate any type of function with an end statement, but doing so is not required unless the file containing the function also contains one or more nested functions. Within this file, every function (including primary, nested, private, and subfunctions) must be terminated with an end.
Functions normally return when the end of the function is reached. Use a return statement to force an early return.
When MATLAB does not recognize a function by name, it searches for a file of the same name on disk. If the function is found, MATLAB compiles it into memory for subsequent use. The section Determining Which Function Gets Called in the MATLAB Programming Fundamentals documentation explains how MATLAB interprets variable and function names that you enter, and also covers the precedence used in function dispatching.
When you call a function from the command line or from another function, MATLAB parses the function and stores it in memory. The parsed function remains in memory until cleared with the clear command or you quit MATLAB. The pcode command performs the parsing step and stores the result on the disk as a P-file to be loaded later.
Examples
Example 1
The existence of a file on disk called stat.m containing this code defines a new function called stat that calculates the mean and standard deviation of a vector:
function [mean,stdev] = stat(x)
n = length(x);
mean = sum(x)/n;
stdev = sqrt(sum((x-mean).^2/n));
Call the function, supplying two output variables on the left side of the equation:
[mean stdev] = stat([12.7 45.4 98.9 26.6 53/1])
mean =
47.3200
stdev =
29.4085
Example 2
avg is a subfunction within the file stat.m:
function [mean,stdev] = stat2(x)
n = length(x);
mean = avg(x,n);
stdev = sqrt(sum((x-avg(x,n)).^2)/n);

function mean = avg(x,n)
mean = sum(x)/n;
Call the function and compare the answer with that of Example 1, above:
[mean stdev] = stat2([12.7 45.4 98.9 26.6 53/1])
mean =
47.3200
stdev =
29.4085


fzero -Find root of continuous function of one variable
Syntax
x = fzero(fun,x0)
x = fzero(fun,x0,options)
[x,fval] = fzero(...)
[x,fval,exitflag] = fzero(...)
[x,fval,exitflag,output] = fzero(...)
Description
x = fzero(fun,x0) tries to find a zero of fun near x0, if x0 is a scalar. fun is a function handle. See Function Handles in the MATLAB Programming documentation for more information. The value x returned by fzero is near a point where fun changes sign, or NaN if the search fails. In this case, the search terminates when the search interval is expanded until an Inf, NaN, or complex value is found.
Parameterizing Functions in the MATLAB Mathematics documentation, explains how to pass additional parameters to your objective function fun. See alsoExample 2 and Example 3 below.
If x0 is a vector of length two, fzero assumes x0 is an interval where the sign of fun(x0(1)) differs from the sign of fun(x0(2)). An error occurs if this is not true. Calling fzero with such an interval guarantees fzero will return a value near a point where fun changes sign.
x = fzero(fun,x0,options) minimizes with the optimization parameters specified in the structure options. You can define these parameters using theoptimset function. fzero uses these options structure fields:
Display Level of display. 'off' displays no output; 'iter' displays output at each iteration; 'final' displays just the final output; 'notify' (default) displays output only if the function does not converge. See Iterative Display in MATLAB Mathematics for more information.
FunValCheck Check whether objective function values are valid. 'on' displays an error when the objective function returns a value that is complex or NaN. 'off' (the default) displays no error.
OutputFcn User-defined function that is called at each iteration. See Output Functions in MATLAB Mathematics for more information.
PlotFcns Plots various measures of progress while the algorithm executes, select from predefined plots or write your own. Pass a function handle or a cell array of function handles. The default is none ([]).
 @optimplotx plots the current point
 @optimplotfval plots the function value
See Plot Functions in MATLAB Mathematics for more information.

TolX Termination tolerance on x
[x,fval] = fzero(...) returns the value of the objective function fun at the solution x.
[x,fval,exitflag] = fzero(...) returns a value exitflag that describes the exit condition of fzero:
1 Function converged to a solution x.
-1 Algorithm was terminated by the output function.
-3 NaN or Inf function value was encountered during search for an interval containing a sign change.
-4 Complex function value was encountered during search for an interval containing a sign change.
-5 fzero might have converged to a singular point.
-6 fzero can not detect a change in sign of the function.
[x,fval,exitflag,output] = fzero(...) returns a structure output that contains information about the optimization in the following fields:
algorithm 'bisection, interpolation'
funcCount Number of function evaluations
intervaliterations Number of iterations to find an interval where fun changes sign
iterations Number of zero-finding iterations
message Exit message
Note For the purposes of this command, zeros are considered to be points where the function actually crosses, not just touches, the x-axis.
Arguments
fun is the function whose zero is to be computed. It accepts a scalar x and returns a scalar f, the objective function evaluated at x. The function fun can be specified as a function handle for a function
x = fzero(@myfun,x0);
where myfun is a function such as
function f = myfun(x)
f = ... % Compute function value at x
or as a function handle for an anonymous function:
x = fzero(@(x)sin(x*x),x0);
Other arguments are described in the syntax descriptions above.
Examples
Example 1
Calculate π by finding the zero of the sine function near 3.
x = fzero(@sin,3)
x =
3.1416
Example 2
To find the zero of cosine between 1 and 2
x = fzero(@cos,[1 2])
x =
1.5708
Note that cos(1) and cos(2) differ in sign.
Example 3
To find a zero of the function f(x) = x3 – 2x – 5, write an anonymous function f:
f = @(x)x.^3-2*x-5;
Then find the zero near 2:
z = fzero(f,2)
z =
2.0946
Because this function is a polynomial, the statement roots([1 0 -2 -5]) finds the same real zero, and a complex conjugate pair of zeros.
2.0946
-1.0473 + 1.1359i
-1.0473 - 1.1359i
If fun is parameterized, you can use anonymous functions to capture the problem-dependent parameters. For example, suppose you want to minimize the objective function myfun defined by the following function file:
function f = myfun(x,a)
f = cos(a*x);
Note that myfun has an extra parameter a, so you cannot pass it directly to fzero. To optimize for a specific value of a, such as a = 2.
1. Assign the value to a.
a = 2; % define parameter first
2. Call fzero with a one-argument anonymous function that captures that value of a and calls myfun with two arguments:
x = fzero(@(x) myfun(x,a),0.1)
Algorithms
The fzero command is a function file. The algorithm, which was originated by T. Dekker, uses a combination of bisection, secant, and inverse quadratic interpolation methods. An Algol 60 version, with some improvements, is given in [1]. A Fortran version, upon which the fzero function file is based, is in[2].
Limitations
The fzero command finds a point where the function changes sign. If the function is continuous, this is also a point where the function has a value near zero. If the function is not continuous, fzero may return values that are discontinuous points instead of zeros. For example, fzero(@tan,1) returns1.5708, a discontinuous point in tan.
Furthermore, the fzero command defines a zero as a point where the function crosses the x-axis. Points where the function touches, but does not cross, the x-axis are not valid zeros. For example, y = x.^2 is a parabola that touches the x-axis at 0. Because the function never crosses the x-axis, however, no zero is found. For functions with no valid zeros, fzero executes until Inf, NaN, or a complex value is detected.

ginput -Graphical input from mouse or cursor
Syntax
[x,y] = ginput(n)
[x,y] = ginput
[x,y,button] = ginput(...)
Description
ginput raises crosshairs in the current axes to for you to identify points in the figure, positioning the cursor with the mouse. The figure must have focus before ginput can receive input. If it has no axes, one is created upon the first click or keypress.
[x,y] = ginput(n) enables you to identify n points from the current axes and returns their x- and y-coordinates in the x and y column vectors. Press the Return key to terminate the input before entering n points.
[x,y] = ginput gathers an unlimited number of points until you press the Return key.
[x,y,button] = ginput(...) returns the x-coordinates, the y-coordinates, and the button or key designation. button is a vector of integers indicating which mouse buttons you pressed (1 for left, 2 for middle, 3 for right), or ASCII numbers indicating which keys on the keyboard you pressed.
Clicking an axes makes that axes the current axes. Even if you set the current axes before calling ginput, whichever axes you click becomes the current axes and ginput returns points relative to that axes. If you select points from multiple axes, the results returned are relative to the coordinate system of the axes they come from.
Definitions
Coordinates returned by ginput are scaled to the XLim and YLim bounds of the axes you click (data units). Setting the axes or figure Units property has no effect on the output from ginput. You can click anywhere within the figure canvas to obtain coordinates. If you click outside the axes limits,ginput extrapolates coordinate values so they are still relative to the axes origin.
The figure CurrentPoint property, by contrast, is always returned in figure Units, irrespective of axes Units or limits.
Examples
Pick 4 two-dimensional points from the figure window.
[x,y] = ginput(4)
Position the cursor with the mouse. Enter data points by pressing a mouse button or a key on the keyboard. To terminate input before entering 4 points, press the Return key.
x =
0.2362
0.5749
0.5680
0.2707

y =
0.6711
0.6769
0.4313
0.4401

plot(x,y)

In this example, plot rescaled the axes x-limits and y-limits from [0 1] and [0 1] to [0.20 0.65] and [0.40 0.75]. The rescaling occured because the axes XLimMode and YLimMode are set to 'auto' (the default). Consider setting XLimMode and YLimMode to 'manual' if you want to maintain consistency when you gather results from ginput and plot them together.



global -Declare global variables
Syntax
global X Y Z
Description
global X Y Z defines X, Y, and Z as global in scope.
Ordinarily, each MATLAB function has its own local variables, which are separate from those of other functions, and from those of the base workspace. However, if several functions, and possibly the base workspace, all declare a particular name as global, they all share a single copy of that variable. Any assignment to that variable, in any function, is available to all the functions declaring it global.
If the global variable does not exist the first time you issue the global statement, it is initialized to the empty matrix.
If a variable with the same name as the global variable already exists in the current workspace, MATLAB issues a warning and changes the value of that variable to match the global.
Tips
Use clear global variable to clear a global variable from the global workspace. Use clear variable to clear the global link from the current workspace without affecting the value of the global.
To use a global within a callback, declare the global, use it, then clear the global link from the workspace. This avoids declaring the global after it has been referenced. For example,
cbstr = sprintf('%s, %s, %s, %s, %s', ...
'global MY_GLOBAL', ...
'MY_GLOBAL = 100', ...
'disp(MY_GLOBAL)', ...
'MY_GLOBAL = MY_GLOBAL+1', ...
'clear MY_GLOBAL');

uicontrol('style', 'pushbutton', 'CallBack', cbstr, ...
'string', 'count')
There is no function form of the global command (i.e., you cannot use parentheses and quote the variable names).
Examples
Example 1
Type edit global_demo1 at the command line and enter the following function definition in the file that opens. This function declares a global variable named globalvar. If you pass a value when calling the function, the function stores the value in globalvar and then displays it. If you call the function with no arguments, the function just displays the value last written to the global workspace:
function global_demo1(num)
global globalvar

if nargin > 0
globalvar = num;
end

fprintf('Global variable in function %s is %d\n', ...
mfilename, globalvar);
Create another function global_demo2 just like it. These two functions have separate function workspaces, but share a common global workspace:
copyfile global_demo1 global_demo2
Call global_demo1, passing a numeric value. Then call global_demo2 with no value. You can see that the latter function has global access to the value that was passed to global_demo1.
global_demo1(1357);
Global variable in function global_demo1 is 1357

global_demo2
Global variable in function global_demo2 is 1357
Now set the value in global_demo2 and read it in global_demo1:
global_demo2(2468)
Global variable in function global_demo2 is 2468

global_demo1
Global variable in function global_demo1 is 2468
Example 2
Call the function global_demo1 that was defined in the previous example to assign a value to variable globalvar in the global workspace. Even though the variable is global, it is not accessible outside of the function workspace:
clear all
global_demo1(1357);
Global variable in function global_demo1 is 1357

if exist('globalvar', 'var')
fprintf('Global variable is set to %d\n', globalvar);
else
fprintf('Global variable is not available at the command line.\n');
end

Global variable is not available at the command line.
Now declare globalvar as a global variable at the MATLAB command line. Run the same statements to display the variable and this time you can see that the value assigned by the function is also available as a global variable in the base workspace:
global globalvar

if exist('globalvar', 'var')
fprintf('Global variable is set to %d\n', globalvar);
else
fprintf(Global variable is not available at the command line.\n');
end

Global variable is set to 1357
Example 3
Here is the code for the functions tic and toc (some comments abridged). These functions manipulate a stopwatch-like timer. The global variableTICTOC is shared by the two functions, but it is invisible in the base workspace or in any other functions that do not declare it.
function tic
% TIC Start a stopwatch timer.
% TIC; any stuff; TOC
% prints the time required.
% See also: TOC, CLOCK.
global TICTOC
TICTOC = clock;

function t = toc
% TOC Read the stopwatch timer.
% TOC prints the elapsed time since TIC was used.
% t = TOC; saves elapsed time in t, does not print.
% See also: TIC, ETIME.
global TICTOC
if nargout < 1 elapsed_time = etime(clock, TICTOC) else t = etime(clock, TICTOC); end grid -Grid lines for 2-D and 3-D plots Alternatives To control the presence and appearance of grid lines on a graph, use the Property Editor, one of the plotting tools . For details, see The Property Editor in the MATLAB Graphics documentation. Syntax grid on grid off grid grid(axes_handle,...) grid minor Description The grid function turns the current axes' grid lines on and off. grid on adds major grid lines to the current axes. grid off removes major and minor grid lines from the current axes. grid toggles the major grid visibility state. grid(axes_handle,...) uses the axes specified by axes_handle instead of the current axes. Algorithms grid sets the XGrid, YGrid, and ZGrid properties of the axes. grid minor sets the XMinorGrid, YMinorGrid, and ZMinorGrid properties of the axes. You can set the grid lines for just one axis using the set command and the individual property. For example, set(axes_handle,'XGrid','on') turns on only x-axis grid lines. You can set grid line width with the axes LineWidth property. By default, the number of grid lines changes when you resize a figure. To prevent this and keep grids the same at any size, set the XTickMode orYTickMode axes properties to 'manual': set(axes_handle,'XTickMode','manual') set(axes_handle,'YTickMode','manual') To customize the locations of ticks along an axis, set the axes XTick, YTick, and ZTick properties. For minor ticks, use the XMinorTick, YMinorTick, and ZTick properties. Examples Create multiple plots within a single figure and manipulate their grid visibility using the grid function: figure subplot(2,2,1) plot(rand(1,20)) title('grid off') subplot(2,2,2) plot(rand(1,20)) grid on title('grid on') subplot(2,2,[3 4]) plot(rand(1,20)) grid(gca,'minor') title('grid minor') You can also use the following code to control grids on a per-axis basis: set(axh,'XGrid','on','YGrid','on','ZGrid','on') gtext -Mouse placement of text in 2-D view Syntax gtext('string') gtext({'string1','string2','string3',...}) gtext({'string1';'string2';'string3';...}) h = gtext(...) Description gtext displays a text string in the current figure window after you select a location with the mouse. gtext('string') waits for you to press a mouse button or keyboard key while the pointer is within a figure window. Pressing a mouse button or any key places 'string' on the plot at the selected location. gtext({'string1','string2','string3',...}) places all strings with one click, each on a separate line. gtext({'string1';'string2';'string3';...}) places one string per click, in the sequence specified. h = gtext(...) returns the handle to a text graphics object that is placed on the plot at the location you select. Tips As you move the pointer into a figure window, the pointer becomes crosshairs to indicate that gtext is waiting for you to select a location. gtext uses the functions ginput and text. Examples Place a label on the current plot: gtext('Note this divergence!') help -Help for functions in Command Window Alternatives Use the Function Browser by clicking its button, , or run doc functionname to view more extensive help for a function in the Help browser. Syntax help help ops help functionname help modelname.mdl help methodname help classname help packagename help classname.name help packagename.classname.name help toolboxname help syntax t = help('topic') Description help lists all primary help topics in the Command Window. Each main help topic corresponds to a folder name on the search path the MATLAB software uses. help ops lists all operators and special characters, along with their descriptions. help functionname displays a brief description and the syntax for functionname in the Command Window. The information is known as the help comments because it comes from the comments at the top of the MATLAB function file. For more information or related help, use the links in the help output. If functionname is overloaded, that is, appears in multiple folders on the search path, help displays the help comments for the firstfunctionname found on the search path, and displays a hyperlinked list of the overloaded functions and their folders. If functionname is also the name of a toolbox, help also displays a list of subfolders and hyperlinked list of functions in the toolbox, as defined in the Contents.m file for the toolbox. help modelname.mdl displays the complete description for the MDL-file modelname as defined in Model Properties > Description. If the Simulink product is installed, you do not need to specify the .mdl extension.
help methodname displays help for the method methodname. You may need to qualify methodname with its class.
help classname displays help for the class classname. You may need to qualify classname with its package.
help packagename displays help for the package packagename.
help classname.name displays help for the method, property, or event name in classname. You may need to qualify classname with its package.
help packagename.classname.name displays help for the method, property, or event name in classname, which is part of packagename. If you do not know the packangename, create an instance of classname and then run class(obj).
help toolboxname displays the Contents.m file for the specified folder named toolboxname, where Contents.m contains a list and corresponding description of MATLAB program files in folder toolboxname. toolboxname can be a partial path. If toolboxname is also a function name, help also displays the help comments for the function. If no toolboxname/Contents.m exists, MATLAB lists the first lines of each program file in the foldertoolboxname. If toolboxname/Contents.m exists but is empty, MATLAB responds with No help found for foldername.
help syntax displays help comments describing the syntax used in MATLAB functions.
t = help('topic') returns the help text for topic as a string, with each line separated by /n, where topic is any allowable argument for help.
Note Some Command Window help text displays the names of functions in uppercase characters to make them stand out from the rest of the text. When typing these function names, use lowercase characters.
Some names use mixed case. The help comments accurately reflect that. Use mixed case when typing these names. For example, the javaObjectfunction uses mixed case.

Tips
Prevent Scrolling of Long Help Pages
To prevent long descriptions from scrolling off the screen before you have time to read them, enter more on, and then enter the help statement.
Examples
help close displays help for the close function. It lists syntaxes for close, and includes hyperlinks to overloaded methods named close and the related delete function.
help database.close displays help for the close function in the Database Toolbox™ product.
help throwAsCaller displays help for the MException.throwAsCaller method.
help MException displays help for the MException class.
help MException.cause displays help for the cause property of the MException class.
help containers displays help for the containers package.
help containers.Map displays help for the Map class in the containers package. Note that help Map does not provide help for the Map class, so include the packagename in the syntax.
help containers.Map.KeyType displays help for the KeyType property. Note that help Map.KeyType do not provide help for KeyType , so include thepackagename in the syntax.
help datafeed displays help for the Datafeed Toolbox™ product.
help database lists the functions in the Database Toolbox product and displays help for the database function, because there is both a function and a toolbox called database.
help general lists all functions in the folder matlabroot/toolbox/matlab/general. This illustrates how to specify a partial path name rather than a full path name.
help f14_dap displays the description of the Simulink f14_dap.mdl model file (the Simulink product must be installed).
t = help('magic') stores help text for magic in variable t:
t =

MAGIC Magic square.
MAGIC(N) is an N-by-N matrix constructed from the integers
1 through N^2 with equal row, column, and diagonal sums.
Produces valid magic squares for all N > 0 except N = 2.

home -Send cursor home
Syntax
home
Description
home moves the cursor to the upper-left corner of the window. When using the MATLAB desktop, home also scrolls the visible text in the window up and out of view. You can use the scroll bar to see what was previously on the screen.
Examples
Execute a MATLAB command that displays something in the Command Window and then run the home function. home moves the cursor to the upper-left corner of the screen and clears the screen.
magic(5)

ans =

17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
home
If -Model if-else control flow
Library
Ports & Subsystems
Description
The If block, along with If Action subsystems containing Action Port blocks, implements standard C-like if-else logic.
The following shows a completed if-else control flow statement.

In this example, the inputs to the If block determine the values of conditions represented as output ports. Each output port is attached to an If Action subsystem. The conditions are evaluated top down starting with the if condition. If a condition is true, its If Action subsystem is executed and the If block does not evaluate any remaining conditions.
The preceding if-else control flow statement can be represented by the following pseudocode.
if (u1 > 0) {
body_1;
}
else if (u2 > 0){
body_2;
}
else {
body_3;
}
You construct a Simulink if-else control flow statement like the preceding example as follows:
1. Place an If block in the current system.
2. Open the dialog of the If block and enter as follows:
 Enter the Number of inputs field with the required number of inputs necessary to define conditions for the if-else control flow statement.
Elements of vector inputs can be accessed for conditions using (row, column) arguments. For example, you can specify the fifth element of the vector u2 in the condition u2(5) > 0 in an If expression or Elseif expressions field.
 Enter the expression for the if condition of the if-else control flow statement in the If expression field.
This creates an if output port for the If block with a label of the form if(condition). This is the only required If Action signal output for an If block.
 Enter expressions for any elseif conditions of the if-else control flow statement in the Elseif expressions field.
Use a comma to separate one condition from another. Entering these conditions creates an output port for the If block for each condition, with a label of the form elseif(condition). elseif ports are optional and not required for operation of the If block.
 Check the Show else condition check box to create an else output port.
The else port is optional and not required for the operation of the If block.
3. Create If Action subsystems to connect to each of the if, else, and elseif ports.
These consist of a subsystem with an Action Port block. When you place an Action Port block inside each subsystem, an input port named Action is added to the subsystem.
4. Connect each if, else, and elseif port of the If block to the Action port of an If Action subsystem.
When you make the connection, the icon for the If Action block is renamed to the type of the condition that it attaches to.
Note During simulation of an if-else control flow statement, the Action signal lines from the If block to the If Action subsystems turn from solid to dashed.
5. In each If Action subsystem, enter the Simulink blocks appropriate to the body to be executed for the condition it handles.
Note All blocks in an If Action Subsystem must run at the same rate as the driving If block. You can achieve this by setting each block's sample time parameter to be either inherited (-1) or the same value as the If block's sample time.
6. In the preceding example, the If Action subsystems are named body_1, body_2, and body_3.
Data Type Support
Inputs u1,u2,...,un can be scalars or vectors of any built-in Simulink data type and must all be of the same data type. The inputs cannot be of any user-defined type, such as an enumerated type. Outputs from the if, else, and elseif ports are Action signals to If Action subsystems that you create by using Action Port blocks and subsystems.
For more information, see Data Types Supported by Simulink in the Simulink documentation.
Parameters and Dialog Box

Number of inputs
Specify the number of inputs to the If block. These appear as data input ports labeled with a 'u' character followed by a number, 1,2,...,n, where n equals the number of inputs that you specify.
If expression
Specify the condition for the if output port. This condition appears on the If block adjacent to the if output port. The if expression can use any of the following operators: <. <=, ==, ~=, >, >=, &, |, ~, (), unary-minus. The If Action subsystem attached to the if port executes if its condition is true. The expression must not contain data type expressions, for example, int8(6), and must not reference workspace variables whose data type is other than double or single.
Note You cannot tune this expression during simulation in Normal or Accelerator mode (see How the Acceleration Modes Work), or in generated code.
The If block does not support custom storage classes. See Custom Storage Classes in the Embedded Coder documentation.

Elseif expressions
Specify a string list of elseif conditions delimited by commas. These conditions appear below the if port and above the else port when you select the Show else condition check box. elseif expressions can use any of the following operators: <, <=, ==, ~=, >, >=, &, |, ~, (), unary-minus. The If Action subsystem attached to an elseif port executes if its condition is true and all of the if and elseif conditions are false. The expression must not contain data type expressions, for example, int8(6), and must not reference workspace variables whose data type is other than double or single.
Note You cannot tune these expressions during simulation in Normal or Accelerator mode (see How the Acceleration Modes Work), or in generated code.

Show else condition
If you select this check box, an else port is created. The If Action subsystem attached to the else port executes if the if port and all the elseifports are false.
Enable zero-crossing detection
Select to enable zero-crossing detection. For more information, see Zero-Crossing Detection.
Sample time
Specify the sample time of the input signal. See How to Specify the Sample Time in the online documentation for more information.
Examples
The If block does not directly support fixed-point data types. However, you can use the Compare To Constant block to work around this limitation.
For example, consider the following floating-point model:

In this model, the If Action subsystems use their default configurations. The block and simulation parameters for the model are set to their default values except as follows:
Block or Dialog Box Parameter Setting
Configuration Parameters — Solver pane Start time 0.0
Stop time 1.0
Type Fixed-step
Solver discrete (no continuous states)
Fixed-step size 0.1
Repeating Sequence Stair Vector of output values [-2 -1 1 2].'
Repeating Sequence Stair1 Vector of output values [0 0 0 0 1 1 1 1].'
If Number of inputs 2
If expression (u1 > 0) | (u2 > 0.5)
Show else condition selected
Constant Constant value -4
Constant1 Constant value 4
Scope Number of axes 3
Time range 1
For this model, if input u1 is greater than 0 or input u2 is greater than 0.5, the output is 4. Otherwise, the output is –4. The Scope block shows the output,u1, and u2:

You can implement this block diagram as a model with fixed-point data types:

The Repeating Sequence Stair blocks now output fixed-point data types.
The Compare To Constant blocks implement two parts of the If expression that is used in the If block in the floating-point version of the model, (u1 > 0) and (u2 > 0.5). The OR operation, (u1|u2), can still be implemented inside the If block. For a fixed-point model, the expression must be partially implemented outside of the If block as it is here.
The block and simulation parameters for the fixed-point model are the same as for the floating-point model with the following exceptions and additions:
Block Parameter Setting
Compare To Constant Operator >
Constant value 0
Output data type mode Boolean
Enable zero-crossing detection off
Compare To Constant1 Operator >
Constant value 0.5
Output data type mode Boolean
Enable zero-crossing detection off
If Number of inputs 2
If expression u1|u2
Characteristics
Direct Feedthrough Yes
Sample Time Inherited from driving block
Scalar Expansion No
Dimensionalized Yes
Zero-Crossing Detection Yes, if enabled



imag -Imaginary part of complex number
Syntax
Y = imag(Z)
Description
Y = imag(Z) returns the imaginary part of the elements of array Z.
Examples
imag(2+3i)

ans = 3

input -Request user input
Syntax
evalResponse = input(prompt)
strResponse = input(prompt, 's')
Description
evalResponse = input(prompt) displays the prompt string on the screen, waits for input from the keyboard, evaluates any expressions in the input, and returns the value in evalResponse. To evaluate expressions, the input function accesses variables in the current workspace.
strResponse = input(prompt, 's') returns the entered text as a MATLAB string, without evaluating expressions.
Tips
 If you press the Return key without entering anything, input returns an empty matrix.
 To create a prompt that spans several lines, use '\n' to indicate each new line. To include a backslash ('\') in the prompt, use '\\'.
 If you enter an invalid expression at the prompt, MATLAB displays the relevant error message and then redisplays the prompt.
Examples
Request a text response. Assign a default value ('Y') by checking for an empty matrix.
reply = input('Do you want more? Y/N [Y]: ', 's');
if isempty(reply)
reply = 'Y';
end

max -Largest elements in array
Syntax
C = max(A)
C = max(A,B)
C = max(A,[],dim)
[C,I] = max(...)
Description
C = max(A) returns the largest elements along different dimensions of an array.
If A is a vector, max(A) returns the largest element in A.
If A is a matrix, max(A) treats the columns of A as vectors, returning a row vector containing the maximum element from each column.
If A is a multidimensional array, max(A) treats the values along the first non-singleton dimension as vectors, returning the maximum value of each vector.
C = max(A,B) returns an array the same size as A and B with the largest elements taken from A or B. The dimensions of A and B must match, or they may be scalar.
C = max(A,[],dim) returns the largest elements along the dimension of A specified by scalar dim. For example, max(A,[],1) produces the maximum values along the first dimension of A.
[C,I] = max(...) finds the indices of the maximum values of A, and returns them in output vector I. If there are several identical maximum values, the index of the first one found is returned.
Examples
Return the maximum of a 2-by-3 matrix from each column:
X = [2 8 4; 7 3 9];
max(X,[],1)
ans =

7 8 9
Return the maximum from each row:
max(X,[],2)
ans =

8
9
Compare each element of X to a scalar:
max(X,5)
ans =

5 8 5
7 5 9
Tips
For complex input A, max returns the complex number with the largest complex modulus (magnitude), computed with max(abs(A)). Then computes the largest phase angle with max(angle(x)), if necessary.
The max function ignores NaNs.


min -Smallest elements in array
Syntax
C = min(A)
C = min(A,B)
C = min(A,[],dim)
[C,I] = min(...)
Description
C = min(A) returns the smallest elements along different dimensions of an array.
If A is a vector, min(A) returns the smallest element in A.
If A is a matrix, min(A) treats the columns of A as vectors, returning a row vector containing the minimum element from each column.
If A is a multidimensional array, min operates along the first nonsingleton dimension.
C = min(A,B) returns an array the same size as A and B with the smallest elements taken from A or B. The dimensions of A and B must match, or they may be scalar.
C = min(A,[],dim) returns the smallest elements along the dimension of A specified by scalar dim. For example, min(A,[],1) produces the minimum values along the first dimension of A.
[C,I] = min(...) finds the indices of the minimum values of A, and returns them in output vector I. If there are several identical minimum values, the index of the first one found is returned.
Examples
Return the minimum of a 2-by-3 matrix from each column:
X = [2 8 4; 7 3 9];
min(X,[],1)
ans =

2 3 4
Return the minimum from each row:
min(X,[],2)
ans =

2
3
Compare each element of X to a scalar:
min(X,5)
ans =

2 5 4
5 3 5
Tips
For complex input A, min returns the complex number with the smallest complex modulus (magnitude), computed with min(abs(A)). Then computes the smallest phase angle with min(angle(x)), if necessary.
The min function ignores NaNs.


mean -Average or mean value of array
Syntax
M = mean(A)
M = mean(A,dim)
Description
M = mean(A) returns the mean values of the elements along different dimensions of an array.
If A is a vector, mean(A) returns the mean value of A.
If A is a matrix, mean(A) treats the columns of A as vectors, returning a row vector of mean values.
If A is a multidimensional array, mean(A) treats the values along the first non-singleton dimension as vectors, returning an array of mean values.
M = mean(A,dim) returns the mean values for elements along the dimension of A specified by scalar dim. For matrices, mean(A,2) is a column vector containing the mean value of each row.
Examples
A = [1 2 3; 3 3 6; 4 6 8; 4 7 7];
mean(A)
ans =
3.0000 4.5000 6.0000

mean(A,2)
ans =
2.0000
4.0000
6.0000
6.0000


median -Median value of array
Syntax
M = median(A)
M = median(A,dim)
Description
M = median(A) returns the median values of the elements along different dimensions of an array. A should be of type single or double.
If A is a vector, median(A) returns the median value of A.
If A is a matrix, median(A) treats the columns of A as vectors, returning a row vector of median values.
If A is a multidimensional array, median(A) treats the values along the first nonsingleton dimension as vectors, returning an array of median values.
M = median(A,dim) returns the median values for elements along the dimension of A specified by scalar dim.
Examples
A = [1 2 4 4; 3 4 6 6; 5 6 8 8; 5 6 8 8];
median(A)

ans =

4 5 7 7

median(A,2)

ans =

3
5
7
7


std -Standard deviation
Syntax
s = std(X)
s = std(X,flag)
s = std(X,flag,dim)
Definitions
There are two common textbook definitions for the standard deviation s of a data vector X.

where

and is the number of elements in the sample. The two forms of the equation differ only in versus in the divisor.
Description
s = std(X), where X is a vector, returns the standard deviation using (1) above. The result s is the square root of an unbiased estimator of the variance of the population from which X is drawn, as long as X consists of independent, identically distributed samples.
If X is a matrix, std(X) returns a row vector containing the standard deviation of the elements of each column of X. If X is a multidimensional array,std(X) is the standard deviation of the elements along the first nonsingleton dimension of X.
s = std(X,flag) for flag = 0, is the same as std(X). For flag = 1, std(X,1) returns the standard deviation using (2) above, producing the second moment of the set of values about their mean.
s = std(X,flag,dim) computes the standard deviations along the dimension of X specified by scalar dim. Set flag to 0 to normalize Y by n-1; set flagto 1 to normalize by n.
Examples
For matrix X
X =
1 5 9
7 15 22
s = std(X,0,1)
s =
4.2426 7.0711 9.1924
s = std(X,0,2)
s =
4.000
7.5056
menu -Generate menu of choices for user input
Syntax
choice = menu('mtitle','opt1','opt2',...,'optn')
choice = menu('mtitle',options)
Description
choice = menu('mtitle','opt1','opt2',...,'optn') displays the menu whose title is in the string variable 'mtitle' and whose choices are string variables 'opt1', 'opt2', and so on. The menu opens in a modal dialog box. menu returns the number of the selected menu item, or 0 if the user clicks the close button on the window.
choice = menu('mtitle',options) , where options is a 1-by-N cell array of strings containing the menu choices.
If the user's terminal provides a graphics capability, menu displays the menu items as push buttons in a figure window (Example 1). Otherwise. they will be given as a numbered list in the Command Window (Example 2).
Tips
To call menu from a uicontrol or other ui object, set that object's Interruptible property to 'on'. For more information, see Uicontrol Properties.
Examples
Example 1
On a system with a display, menu displays choices as buttons in a dialog box:
choice = menu('Choose a color','Red','Blue','Green')
displays the following dialog box.

The number entered by the user in response to the prompt is returned as choice (i.e., choice = 2 implies that the user selected Blue).
After input is accepted, the dialog box closes, returning the output in choice. You can use choice to control the color of a graph:
t = 0:.1:60;
s = sin(t);
color = ['r','g','b']
plot(t,s,color(choice))
Example 2
On a system without a display, menu displays choices in the Command Window:
choice = menu('Choose a color','Red','Blue','Green')
displays the following text.
----- Choose a color -----
1) Red
2) Blue
3) Green
Select a menu number:


ones -Create array of all ones
Syntax
Y = ones(n)
Y = ones(m,n)
Y = ones([m n])
Y = ones(m,n,p,...)
Y = ones([m n p ...])
Y = ones(size(A))
Y = ones
ones(m, n,...,classname)
ones([m,n,...],classname)
Description
Y = ones(n) returns an n-by-n matrix of 1s. An error message appears if n is not a scalar.
Y = ones(m,n) or Y = ones([m n]) returns an m-by-n matrix of ones.
Y = ones(m,n,p,...) or Y = ones([m n p ...]) returns an m-by-n-by-p-by-... array of 1s.
Note The size inputs m, n, p, ... should be nonnegative integers. Negative integers are treated as 0.
Y = ones(size(A)) returns an array of 1s that is the same size as A.
Y = ones with no arguments is the scalar 1.
ones(m, n,...,classname) or ones([m,n,...],classname) is an m-by-n-by-... array of ones of data type classname. classname is a string specifying the data type of the output. classname can have the following values: 'double', 'single', 'int8', 'uint8', 'int16', 'uint16', 'int32','uint32', 'int64', or 'uint64'.
Examples
x = ones(2,3,'int8');

pause -Halt execution temporarily
Syntax
pause
pause(n)
pause on
pause off
pause query
state = pause('query')
oldstate = pause(newstate)
Description
pause, by itself, causes the currently executing function to stop and wait for you to press any key before continuing. Pausing must be enabled for this to take effect. (See pause on, below). pause without arguments also blocks execution of Simulink models, but not repainting of them.
pause(n) pauses execution for n seconds before continuing, where n is any nonnegative real number. Pausing must be enabled for this to take effect.
Typing pause(inf) puts you into an infinite loop. To return to the MATLAB prompt, type Ctrl+C.
pause on enables the pausing of MATLAB execution via the pause and pause(n) commands. Pausing remains enabled until you enter pause off in your function or at the command line.
pause off disables the pausing of MATLAB execution via the pause and pause(n) commands. This allows normally interactive scripts to run unattended. Pausing remains disabled until you enter pause on in your function or at the command line, or start a new MATLAB session.
pause query displays 'on' if pausing is currently enabled. Otherwise, it displays 'off'.
state = pause('query') returns 'on' in character array state if pausing is currently enabled. Otherwise, the value of state is 'off'.
oldstate = pause(newstate), enables or disables pausing, depending on the 'on' or 'off' value in newstate, and returns the former setting (also either 'on' or 'off') in character array oldstate.
Tips
The accuracy of pause is subject to the scheduling resolution of the operating system you are using, and also to other system activity. It cannot be guaranteed with 100% confidence. Asking for finer resolutions shows higher relative error.
While MATLAB is paused, the following continue to execute:
 Repainting of figure windows, Simulink block diagrams, and Java windows
 HG callbacks from figure windows
 Event handling from Java windows
plot -2-D line plot
Syntax
plot(Y)
plot(X1,Y1,...,Xn,Yn)
plot(X1,Y1,LineSpec,...,Xn,Yn,LineSpec)
plot(...,'PropertyName',PropertyValue,...)
plot(axes_handle,...)
h = plot(...)
Description
plot(Y) plots the columns of Y versus the index of each value when Y is a real number. For complex Y, plot(Y) is equivalent toplot(real(Y),imag(Y)).
plot(X1,Y1,...,Xn,Yn) plots each vector Yn versus vector Xn on the same axes. If one of Yn or Xn is a matrix and the other is a vector, it plots the vector versus the matrix row or column with a matching dimension to the vector. If Xn is a scalar and Yn is a vector, it plots discrete Yn points vertically at Xn. If Xn or Yn are complex, imaginary components are ignored. If Xn or Yn are matrices, they must be 2-D and the same size, and the columns of Ynare plotted against the columns of Xn. plot automatically chooses colors and line styles in the order specified by ColorOrder and LineStyleOrderproperties of current axes.
plot(X1,Y1,LineSpec,...,Xn,Yn,LineSpec) plots lines defined by the Xn,Yn,LineSpec triplets, where LineSpec specifies the line type, marker symbol, and color. You can mix Xn,Yn,LineSpec triplets with Xn,Yn pairs: plot(X1,Y1,X2,Y2,LineSpec,X3,Y3).
plot(...,'PropertyName',PropertyValue,...) manipulates plot characteristics by setting lineseries properties (of lineseries graphics objects created by plot). Enter properties as one or more name-value pairs.
plot(axes_handle,...) plots using axes with the handle axes_handle instead of the current axes (gca).
h = plot(...) returns a column vector of handles to lineseries objects, one handle per line.
Tips
Plot data can include NaN and inf values, which cause breaks in the lines drawn. For example,
plot([1:5,NaN,6:10])
Skips the sixth element and resumes line drawing at the seventh element with the Y value of 6.
Examples
Plot a sine curve.
x = -pi:.1:pi;
y = sin(x);
plot(x,y)




Create line plot using specific line width, marker color, and marker size.
x = -pi:pi/10:pi;
y = tan(sin(x)) - sin(tan(x));
plot(x,y,'--rs','LineWidth',2,...
'MarkerEdgeColor','k',...
'MarkerFaceColor','g',...
'MarkerSize',10)







Modify axis tick marks and tick labels and annotate the graph.
x = -pi:.1:pi;
y = sin(x);
plot(x,y)
set(gca,'XTick',-pi:pi/2:pi)
set(gca,'XTickLabel',{'-pi','-pi/2','0','pi/2','pi'})
title('Sine Function');
xlabel('Radians');
ylabel('Function Value');




Add a plot title, axis labels, and annotations.
x = -pi:.1:pi;
y = sin(x);
p = plot(x,y)
set(gca,'XTick',-pi:pi/2:pi)
set(gca,'XTickLabel',{'-pi','-pi/2','0','pi/2','pi'})
xlabel('-\pi \leq \Theta \leq \pi')
ylabel('sin(\Theta)')
title('Plot of sin(\Theta)')
% \Theta appears as a Greek symbol (see String)
% Annotate the point (-pi/4, sin(-pi/4))
text(-pi/4,sin(-pi/4),'\leftarrow sin(-\pi\div4)',...
'HorizontalAlignment','left')
% Change the line color to red and
% set the line width to 2 points
set(p,'Color','red','LineWidth',2)




Plot multiple line plots on the same axes.
plot(sin(x));
% hold axes and all lineseries properties, such as
% ColorOrder and LineStyleOrder, for the next plot
hold all
plot(sin(x+(pi/4)));




Set line color to be always black and line style order to cycle through solid, dash-dot, dash-dash, and dotted line styles.
set(0,'DefaultAxesColorOrder',[0 0 0],...
'DefaultAxesLineStyleOrder','-|-.|--|:')
plot(sin(x))
hold all
plot(cos(x))
hold all
plot(log(abs(x)))

Alternatives
To plot variables in the MATLAB workspace:
1. In the MATLAB workspace browser, select one or more variables.
2. Choose the plot type from the menu.


polyval -Polynomial evaluation
Syntax
y = polyval(p,x)
[y,delta] = polyval(p,x,S)
y = polyval(p,x,[],mu)
[y,delta] = polyval(p,x,S,mu)
Description
y = polyval(p,x) returns the value of a polynomial of degree n evaluated at x. The input argument p is a vector of length n+1 whose elements are the coefficients in descending powers of the polynomial to be evaluated.

x can be a matrix or a vector. In either case, polyval evaluates p at each element of x.
[y,delta] = polyval(p,x,S) uses the optional output structure S generated by polyfit to generate error estimates delta. delta is an estimate of the standard deviation of the error in predicting a future observation at x by p(x). If the coefficients in p are least squares estimates computed bypolyfit, and the errors in the data input to polyfit are independent, normal, and have constant variance, then y±delta contains at least 50% of the predictions of future observations at x.
y = polyval(p,x,[],mu) or [y,delta] = polyval(p,x,S,mu) use in place of x. In this equation, and . The centering and scaling parameters are optional output computed by polyfit.
Tips
The polyvalm(p,x) function, with x a matrix, evaluates the polynomial in a matrix sense. See polyvalm for more information.
Examples
The polynomial is evaluated at x = 5, 7, and 9 with
p = [3 2 1];
polyval(p,[5 7 9])
which results in
ans =

86 162 262
prod -Product of array elements
Syntax
B = prod(A)
B = prod(A,dim)
B = prod(A,'double')
B = prod(A,'native')
Description
B = prod(A) returns the products along different dimensions of an array. A can be double or single. B is multiplied natively, that is in the same class as A, and B has the same class as A.
If A is a vector, prod(A) returns the product of the elements.
If A is a matrix, prod(A) treats the columns of A as vectors, returning a row vector of the products of each column.
If A is a multidimensional array, prod(A) treats the values along the first non-singleton dimension as vectors, returning an array of row vectors.
B = prod(A,dim) takes the products along the dimension of A specified by scalar dim.
B = prod(A,'double') multiplies B in double and B has class double, even if A is single.
B = prod(A,'native') multiplies B natively and B has the same class as A.
Examples
The magic square of order 3 is
M = magic(3)

M =
8 1 6
3 5 7
4 9 2
The product of the elements in each column is
prod(M) =

96 45 84
The product of the elements in each row can be obtained by:
prod(M,2) =

48
105
72

qr -Orthogonal-triangular decomposition
Syntax
[Q,R] = qr(A)
[Q,R] = qr(A,0)
[Q,R,E] = qr(A)
[Q,R,E] = qr(A,'matrix')
[Q,R,e] = qr(A,'vector')
[Q,R,e] = qr(A,0)
X = qr(A)
X = qr(A,0)
R = qr(A)
R = qr(A,0)
[C,R] = qr(A,B)
[C,R,E] = qr(A,B)
[C,R,E] = qr(A,B,'matrix')
[C,R,e] = qr(A,B,'vector')
[C,R] = qr(A,B,0)
[C,R,e] = qr(A,B,0)
Description
[Q,R] = qr(A), where A is m-by-n, produces an m-by-n upper triangular matrix R and an m-by-m unitary matrix Q so that A = Q*R.
[Q,R] = qr(A,0) produces the economy-size decomposition. If m > n, only the first n columns of Q and the first n rows of R are computed. If m<=n, this is the same as [Q,R] = qr(A). If A is full: [Q,R,E] = qr(A) or [Q,R,E] = qr(A,'matrix') produces unitary Q, upper triangular R and a permutation matrix E so that A*E = Q*R. The column permutation E is chosen so that abs(diag(R)) is decreasing. [Q,R,e] = qr(A,'vector') returns the permutation information as a vector instead of a matrix. That is, e is a row vector such that A(:,e) = Q*R. [Q,R,e] = qr(A,0) produces an economy-size decomposition in which e is a permutation vector, so that A(:,e) = Q*R. X = qr(A) and X = qr(A,0) return a matrix X such that triu(X) is the upper triangular factor R. If A is sparse: R = qr(A) computes a Q-less QR decomposition and returns the upper triangular factor R. Note that R = chol(A'*A). Since Q is often nearly full, this is preferred to [Q,R] = QR(A). R = qr(A,0) produces economy-size R. If m>n, R has only n rows. If m<=n, this is the same as R = qr(A). [Q,R,E] = qr(A) or [Q,R,E] = qr(A,'matrix') produces unitary Q, upper triangular R and a permutation matrix E so that A*E = Q*R. The column permutation E is chosen to reduce fill-in in R. [Q,R,e] = qr(A,'vector') returns the permutation information as a vector instead of a matrix. That is, e is a row vector such that A(:,e) = Q*R. [Q,R,e] = qr(A,0) produces an economy-size decomposition in which e is a permutation vector, so that A(:,e) = Q*R. [C,R] = qr(A,B), where B has as many rows as A, returns C = Q'*B. The least-squares solution to A*X = B is X = R\C. [C,R,E] = qr(A,B) or [C,R,E] = qr(A,B,'matrix'), also returns a fill-reducing ordering. The least-squares solution to A*X = B is X = E*(R\C). [C,R,e] = qr(A,B,'vector') returns the permutation information as a vector instead of a matrix. That is, the least-squares solution to A*X = B isX(e,:) = R\C. [C,R] = qr(A,B,0) produces economy-size results. If m>n, C and R have only n rows. If m<=n, this is the same as [C,R] = qr(A,B). [C,R,e] = qr(A,B,0) additionally produces a fill-reducing permutation vector e. In this case, the least-squares solution to A*X = B is X(e,:) = R\C. Examples Find the least squares approximate solution to A*x = b with the Q-less QR decomposition and one step of iterative refinement: if issparse(A), R = qr(A); else R = triu(qr(A)); end x = R\(R'\(A'*b)); r = b - A*x; err = R\(R'\(A'*r)); x = x + err; quad -Numerically evaluate integral, adaptive Simpson quadrature Syntax q = quad(fun,a,b) q = quad(fun,a,b,tol) q = quad(fun,a,b,tol,trace) [q,fcnt] = quad(...) Description Quadrature is a numerical method used to find the area under the graph of a function, that is, to compute a definite integral. q = quad(fun,a,b) tries to approximate the integral of function fun from a to b to within an error of 1e-6 using recursive adaptive Simpson quadrature. fun is a function handle. See Function Handles in the MATLAB Programming documentation for more information. Limits a and b must be finite. The function y = fun(x) should accept a vector argument x and return a vector result y, the integrand evaluated at each element of x. Parameterizing Functions, in the MATLAB Mathematics documentation, explains how to provide additional parameters to the function fun, if necessary. q = quad(fun,a,b,tol) uses an absolute error tolerance tol instead of the default which is 1.0e-6. Larger values of tol result in fewer function evaluations and faster computation, but less accurate results. In MATLAB version 5.3 and earlier, the quad function used a less reliable algorithm and a default relative tolerance of 1.0e-3. q = quad(fun,a,b,tol,trace) with non-zero trace shows the values of [fcnt a b-a Q] during the recursion. [q,fcnt] = quad(...) returns the number of function evaluations. The function quadl may be more efficient with high accuracies and smooth integrands. The list below contains information to help you determine which quadrature function in MATLAB to use:  The quad function may be most efficient for low accuracies with nonsmooth integrands.  The quadl function may be more efficient than quad at higher accuracies with smooth integrands.  The quadgk function may be most efficient for high accuracies and oscillatory integrands. It supports infinite intervals and can handle moderate singularities at the endpoints. It also supports contour integration along piecewise linear paths.  The quadv function vectorizes quad for an array-valued fun.  If the interval is infinite, [a,Inf), then for the integral of fun(x) to exist, fun(x) must decay as x approaches infinity, and quadgk requires it to decay rapidly. Special methods should be used for oscillatory functions on infinite intervals, but quadgk can be used if fun(x) decays fast enough.  The quadgk function will integrate functions that are singular at finite endpoints if the singularities are not too strong. For example, it will integrate functions that behave at an endpoint c like log|x-c| or |x-c|p for p >= -1/2. If the function is singular at points inside (a,b), write the integral as a sum of integrals over subintervals with the singular points as endpoints, compute them with quadgk, and add the results.
Examples
To compute the integral

write a function myfun that computes the integrand:
function y = myfun(x)
y = 1./(x.^3-2*x-5);
Then pass @myfun, a function handle to myfun, to quad, along with the limits of integration, 0 to 2:
Q = quad(@myfun,0,2)

Q =

-0.4605
Alternatively, you can pass the integrand to quad as an anonymous function handle F:
F = @(x)1./(x.^3-2*x-5);
Q = quad(F,0,2);
Algorithms
quad implements a low order method using an adaptive recursive Simpson's rule.
Diagnostics
quad may issue one of the following warnings:
'Minimum step size reached' indicates that the recursive interval subdivision has produced a subinterval whose length is on the order of roundoff error in the length of the original interval. A nonintegrable singularity is possible.
'Maximum function count exceeded' indicates that the integrand has been evaluated more than 10,000 times. A nonintegrable singularity is likely.
'Infinite or Not-a-Number function value encountered' indicates a floating point overflow or division by zero during the evaluation of the integrand in the interior of the interval.


rand -Uniformly distributed pseudorandom numbers
Syntax
r = rand(n)
r = rand(m,n)
r = rand([m,n])
r = rand(m,n,p,...)
r = rand([m,n,p,...])
r = rand
r = rand(size(A))
r = rand(..., 'double')
r = rand(..., 'single')
Description
r = rand(n) returns an n-by-n matrix containing pseudorandom values drawn from the standard uniform distribution on the open interval (0,1). r = rand(m,n) or r = rand([m,n]) returns an m-by-n matrix. r = rand(m,n,p,...) or r = rand([m,n,p,...]) returns an m-by-n-by-p-by-... array. r = rand returns a scalar. r = rand(size(A)) returns an array the same size as A.
r = rand(..., 'double') or r = rand(..., 'single') returns an array of uniform values of the specified class.
Note The size inputs m, n, p, ... should be nonnegative integers. Negative integers are treated as 0.
The sequence of numbers produced by rand is determined by the internal settings of the uniform random number generator that underlies rand, randi, and randn. You can control that shared random number generator using rng.
Note To use the rng function instead of rand or randn with the 'seed', 'state', or 'twister' inputs, see the documentation on Updating Your Random Number Generator Syntax

Examples
Example 1
Generate values from the uniform distribution on the interval [a, b]:
r = a + (b-a).*rand(100,1);
Example 2
Use the randi function, instead of rand, to generate integer values from the uniform distribution on the set 1:100:
r = randi(100,1,5);
Example 3
Reset the random number generator used by rand, randi, and randn to its default startup settings, so that rand produces the same random numbers as if you restarted MATLAB:
rng('default')
rand(1,5)
ans =
0.8147 0.9058 0.1270 0.9134 0.6324
Example 4
Save the settings for the random number generator used by rand, randi, and randn, generate 5 values from rand, restore the settings, and repeat those values:
s = rng;
u1 = rand(1,5)
u1 =
0.0975 0.2785 0.5469 0.9575 0.9649

rng(s);
u2 = rand(1,5)
u2 =
0.0975 0.2785 0.5469 0.9575 0.9649
u2 contains exactly the same values as u1.
Example 5
Reinitialize the random number generator used by rand, randi, and randn with a seed based on the current time. rand returns different values each time you do this. Note that it is usually not necessary to do this more than once per MATLAB session as it may affect the statistical properties of the random numbers MATLAB produces:
rng('shuffle');
rand(1,5);


real -Real part of complex number
Syntax
X = real(Z)
Description
X = real(Z) returns the real part of the elements of the complex array Z.
Examples
real(2+3*i) is 2.


rem -Remainder after division
Syntax
R = rem(X,Y)
Description
R = rem(X,Y) if Y ~= 0, returns X - n.*Y where n = fix(X./Y). If Y is not an integer and the quotient X./Y is within roundoff error of an integer, then n is that integer. The inputs X and Y must be real arrays of the same size, or real scalars.
The following are true by convention:
 rem(X,0) is NaN
 rem(X,X) for X~=0 is 0
 rem(X,Y) for X~=Y and Y~=0 has the same sign as X.
Tips
mod(X,Y) for X~=Y and Y~=0 has the same sign as Y.
rem(X,Y) and mod(X,Y) are equal if X and Y have the same sign, but differ by Y if X and Y have different signs.
The rem function returns a result that is between 0 and sign(X)*abs(Y). If Y is zero, rem returns NaN.


reshape -Reshape array
Syntax
B = reshape(A,m,n)
B = reshape(A,m,n,p,...)
B = reshape(A,[m n p ...])
B = reshape(A,...,[],...)
B = reshape(A,siz)
Description
B = reshape(A,m,n) returns the m-by-n matrix B whose elements are taken column-wise from A. An error results if A does not have m*n elements.
B = reshape(A,m,n,p,...) or B = reshape(A,[m n p ...]) returns an n-dimensional array with the same elements as A but reshaped to have the size m-by-n-by-p-by-.... The product of the specified dimensions, m*n*p*..., must be the same as prod(size(A)).
B = reshape(A,...,[],...) calculates the length of the dimension represented by the placeholder [], such that the product of the dimensions equalsprod(size(A)). The value of prod(size(A)) must be evenly divisible by the product of the specified dimensions. You can use only one occurrence of[].
B = reshape(A,siz) returns an n-dimensional array with the same elements as A, but reshaped to siz, a vector representing the dimensions of the reshaped array. The quantity prod(siz) must be the same as prod(size(A)).
Examples
Reshape a 3-by-4 matrix into a 2-by-6 matrix.
A =
1 4 7 10
2 5 8 11
3 6 9 12

B = reshape(A,2,6)

B =
1 3 5 7 9 11
2 4 6 8 10 12
B = reshape(A,2,[])

B =
1 3 5 7 9 11
2 4 6 8 10 12


residue -Convert between partial fraction expansion and polynomial coefficients
Syntax
[r,p,k] = residue(b,a)
[b,a] = residue(r,p,k)
Description
The residue function converts a quotient of polynomials to pole-residue representation, and back again.
[r,p,k] = residue(b,a) finds the residues, poles, and direct term of a partial fraction expansion of the ratio of two polynomials, and , of the form

where and are the jth elements of the input vectors b and a.
[b,a] = residue(r,p,k) converts the partial fraction expansion back to the polynomials with coefficients in b and a.
Definitions
If there are no multiple roots, then

The number of poles n is
n = length(a)-1 = length(r) = length(p)
The direct term coefficient vector is empty if length(b) < length(a); otherwise length(k) = length(b)-length(a)+1 If p(j) = ... = p(j+m-1) is a pole of multiplicity m, then the expansion includes terms of the form Arguments b,a Vectors that specify the coefficients of the polynomials in descending powers of r Column vector of residues p Column vector of poles k Row vector of direct terms Algorithms It first obtains the poles with roots. Next, if the fraction is nonproper, the direct term k is found using deconv, which performs polynomial long division. Finally, the residues are determined by evaluating the polynomial with individual roots removed. For repeated roots, resi2 computes the residues at the repeated root locations. Limitations Numerically, the partial fraction expansion of a ratio of polynomials represents an ill-posed problem. If the denominator polynomial, , is near a polynomial with multiple roots, then small changes in the data, including roundoff errors, can make arbitrarily large changes in the resulting poles and residues. Problem formulations making use of state-space or zero-pole representations are preferable. Examples If the ratio of two polynomials is expressed as then b = [ 5 3 -2 7] a = [-4 0 8 3] and you can calculate the partial fraction expansion as [r, p, k] = residue(b,a) r = -1.4167 -0.6653 1.3320 p = 1.5737 -1.1644 -0.4093 k = -1.2500 Now, convert the partial fraction expansion back to polynomial coefficients. [b,a] = residue(r,p,k) b = -1.2500 -0.7500 0.5000 -1.7500 a = 1.0000 -0.0000 -2.0000 -0.7500 The result can be expressed as Note that the result is normalized for the leading coefficient in the denominator. roots -Polynomial roots Syntax r = roots(c) Description r = roots(c) returns a column vector whose elements are the roots of the polynomial c. Row vector c contains the coefficients of a polynomial, ordered in descending powers. If c has n+1 components, the polynomial it represents is . Tips Note the relationship of this function to p = poly(r), which returns a row vector whose elements are the coefficients of the polynomial. For vectors,roots and poly are inverse functions of each other, up to ordering, scaling, and roundoff error. Examples The polynomial is represented in MATLAB software as p = [1 -6 -72 -27] The roots of this polynomial are returned in a column vector by r = roots(p) r = 12.1229 -5.7345 -0.3884 Algorithms The algorithm simply involves computing the eigenvalues of the companion matrix: A = diag(ones(n-1,1),-1); A(1,:) = -c(2:n+1)./c(1); eig(A) It is possible to prove that the results produced are the exact eigenvalues of a matrix within roundoff error of the companion matrix A, but this does not mean that they are the exact roots of a polynomial with coefficients within roundoff error of those in c. round -Round to nearest integer Syntax Y = round(X) Description Y = round(X) rounds the elements of X to the nearest integers. Positive elements with a fractional part of 0.5 round up to the nearest positive integer. Negative elements with a fractional part of -0.5 round down to the nearest negative integer. For complex X, the imaginary and real parts are rounded independently. Examples a = [-1.9, -0.2, 3.4, 5.6, 7.0, 2.4+3.6i] a = Columns 1 through 4 -1.9000 -0.2000 3.4000 5.6000 Columns 5 through 6 7.0000 2.4000 + 3.6000i round(a) ans = Columns 1 through 4 -2.0000 0 3.0000 6.0000 Columns 5 through 6 7.0000 2.0000 + 4.0000i shading -Set color shading properties Syntax shading flat shading faceted shading interp shading(axes_handle,...) Description The shading function controls the color shading of surface and patch graphics objects. shading flat each mesh line segment and face has a constant color determined by the color value at the endpoint of the segment or the corner of the face that has the smallest index or indices. shading faceted flat shading with superimposed black mesh lines. This is the default shading mode. shading interp varies the color in each line segment and face by interpolating the colormap index or true color value across the line or face. shading(axes_handle,...) applies the shading type to the objects in the axes specified by axes_handle, instead of the current axes. Use quoted strings when using a function form. For example: shading(gca,'interp') Examples Compare a flat, faceted, and interpolated-shaded sphere. subplot(3,1,1) sphere(16) axis square shading flat title('Flat Shading') subplot(3,1,2) sphere(16) axis square shading faceted title('Faceted Shading') subplot(3,1,3) sphere(16) axis square shading interp title('Interpolated Shading') Algorithms shading sets the EdgeColor and FaceColor properties of all surface and patch graphics objects in the current axes. shading sets the appropriate values, depending on whether the surface or patch objects represent meshes or solid surfaces. sign -Signum function Syntax Y = sign(X) Description Y = sign(X) returns an array Y the same size as X, where each element of Y is:  1 if the corresponding element of X is greater than zero  0 if the corresponding element of X equals zero  -1 if the corresponding element of X is less than zero For nonzero complex X, sign(X) = X./abs(X). size (tscollection) -Size of tscollection object Syntax size(tsc) Description size(tsc) returns [n m], where n is the length of the time vector and m is the number of tscollection members. sort -Sort array elements in ascending or descending order Syntax B = sort(A) B = sort(A,dim) B = sort(...,mode) [B,IX] = sort(A,...) Description B = sort(A) sorts the elements along different dimensions of an array, and arranges those elements in ascending order. If A is a ... sort(A) ... Vector Sorts the elements of A. Matrix Sorts each column of A. Multidimensional array Sorts A along the first non-singleton dimension, and returns an array of sorted vectors. Cell array of strings Sorts the strings in ascending ASCII dictionary order, and returns a vector cell array of strings. The sort is case-sensitive; uppercase letters appear in the output before lowercase. You cannot use the dim or mode options with a cell array. Integer, floating-point, logical, and character arrays are permitted. Floating-point arrays can be complex. For elements of A with identical values, the order of these elements is preserved in the sorted list. When A is complex, the elements are sorted by magnitude, i.e., abs(A), and where magnitudes are equal, further sorted by phase angle, i.e., angle(A), on the interval [−π, π]. If A includes any NaN elements, sort places these at the high end. B = sort(A,dim) sorts the elements along the dimension of A specified by a scalar dim. B = sort(...,mode) sorts the elements in the specified direction, depending on the value of mode. 'ascend' Ascending order (default) 'descend' Descending order [B,IX] = sort(A,...) also returns an array of indices IX, where size(IX) == size(A). If A is a vector, B = A(IX). If A is an m-by-n matrix, then each column of IX is a permutation vector of the corresponding column of A, such that for j = 1:n B(:,j) = A(IX(:,j),j); end If A has repeated elements of equal value, the returned indices preserve the original ordering. Sorting Complex Entries If A has complex entries r and s, sort orders them according to the following rule: r appears before s in sort(A) if either of the following hold:  abs(r) < abs(s)  abs(r) = abs(s) and angle(r) 0 is above the main diagonal, and k < 0 is below the main diagonal. Examples tril(ones(4,4),-1) ans = 0 0 0 0 1 0 0 0 1 1 0 0 1 1 1 0 triu -Upper triangular part of matrix Syntax U = triu(X) U = triu(X,k) Description U = triu(X) returns the upper triangular part of X. U = triu(X,k) returns the element on and above the kth diagonal of X. k = 0 is the main diagonal, k > 0 is above the main diagonal, and k < 0 is below the main diagonal. Examples triu(ones(4,4),-1) ans = 1 1 1 1 1 1 1 1 0 1 1 1 0 0 1 1 type -Display contents of file Syntax type('filename') type filename Description type('filename') displays the contents of the specified file in the MATLAB Command Window. Use the full path for filename, or use a MATLAB relative partial path. If you do not specify a file extension and there is no filename file without an extension, the type function adds the .m extension by default. The typefunction checks the folders specified in the MATLAB search path, which makes it convenient for listing the contents of files on the screen. Use type withmore on to see the listing one screen at a time. type filename is the command form of the syntax. Examples type('foo.bar') lists the contents of the file foo.bar. type foo lists the contents of the file foo. If foo does not exist, type foo lists the contents of the file foo.m. what -List MATLAB files in folder Syntax what what folderName what className what packageName s = what('folderName') Description what lists the path for the current folder, and lists all files and folders relevant to MATLAB found in the current folder. Files listed are M, MAT, MEX, MDL, and P-files. Folders listed are all class and package folders. what folderName lists path, file, and folder information for folderName. what className lists path, file, and folder information for method folder @className. For example, what cfit lists the MATLAB files and folders intoolbox/curvefit/curvefit/@cfit. what packageName lists path, file, and folder information for package folder +packageName. For example, what commsrc lists the MATLAB files and folders in toolbox/comm/comm/+commsrc. s = what('folderName') returns the results in a structure array with the fields shown in the following table. Field Description path Path to folder m Cell array of MATLAB program file names mat Cell array of MAT-file names mex Cell array of MEX-file names mdl Cell array of MDL-file names p Cell array of P-file names classes Cell array of class folders packages Cell array of package folders Examples List the MATLAB files and folders in C:\Program Files\MATLAB\Rnnnn\toolbox\matlab\audiovideo\+audiovideo, where Rnnnn represents the folder for the MATLAB release, for example, R2010b: what audiovideo M-files in directory C:\Program Files\MATLAB\Rnnnn\toolbox\matlab\audiovideo\+audiovideo FileFormatInfo Packages in directory C:\Program Files\MATLAB\Rnnnn\toolbox\matlab\audiovideo\+audiovideo internal writer M-files in directory C:\Program Files\MATLAB\Rnnnn\toolbox\matlab\audiovideo Contents avifinfo sound audiodevinfo aviinfo soundsc audioplayerreg aviread wavfinfo audiorecorderreg lin2mu wavplay audiouniquename mmcompinfo wavread aufinfo mmfileinfo wavrecord auread movie2avi waywrite auwrite mu2lin avgate prefspanel MAT-files in directory C:\Program Files\MATLAB\Rnnnn\toolbox\matlab\audiovideo chirp handel splat gong laughter train MEX-files in directory C:\Program Files\MATLAB\Rnnnn\toolbox\matlab\audiovideo WinAudioPlayer WinAudioRecorder Classes in directory C:\Program Files\MATLAB\Rnnnn\toolbox\matlab\audiovideo VideoReader audioplayer avifile VideoWriter audiorecorder mmreader Packages in directory C:\Program Files\MATLAB\Rnnnn\toolbox\matlab\audiovideo audiovideo Obtain a structure array containing the file and folder names in toolbox/matlab/codetools that are relevant to MATLAB, where Rnnnn represents the folder for the MATLAB release, for example, R2010b: s = what('codetools') s = path: 'C:\Program Files\MATLAB\Rnnnn\toolbox\matlab\codetools' m: {76x1 cell} mat: {0x1 cell} mex: {0x1 cell} mdl: {0x1 cell} p: {0x1 cell} classes: {2x1 cell} packages: {3x1 cell} Find the supporting files for one of the packages in the Communications System Toolbox product: p1 = what('comm'); p1.packages ans = 'measure' ans = 'channel' 'converter' 'ecc' . . . p2 = what('commsrc'); p2.m ans = 'abstractJitter.m' 'abstractPulse.m' 'combinedjitter.m' 'diracjitter.m' 'periodicjitter.m' 'randomjitter.m' Alternatives Use the Current Folder browser to view the list of files in a folder. while -Repeatedly execute statements while condition is true Syntax while expression statements end Description while expression, statements, end repeatedly executes one or more MATLAB program statements in a loop as long as an expression remains true. An evaluated expression is true when the result is nonempty and contains all nonzero elements (logical or real numeric). Otherwise, the expression is false. Expressions can include relational operators (such as < or ==) and logical operators (such as &&, ||, or ~). MATLAB evaluates compound expressions from left to right, adhering to operator precedence rules. Tips  If you inadvertently create an infinite loop (that is, a loop that never ends on its own), stop execution of the loop by pressing Ctrl+C.  To programmatically exit the loop, use a break statement. To skip the rest of the instructions in the loop and begin the next iteration, use a continuestatement.  You can nest any number of while statements. Each while statement requires an end keyword.  Within an if or while expression, all logical operators, including | and &, short-circuit. That is, if the first part of the expression determines a true or false result, MATLAB does not evaluate the second part of the expression. Examples Find the first integer n for which factorial(n) is a 100-digit number: n = 1; nFactorial = 1; while nFactorial < 1e100 n = n + 1; nFactorial = nFactorial * n; end Count the number of lines of code in the file magic.m, skipping all blank lines and comments: fid = fopen('magic.m','r'); count = 0; while ~feof(fid) line = fgetl(fid); if isempty(line) || strncmp(line,'%',1) || ~ischar(line) continue end count = count + 1; end fprintf('%d lines\n',count); fclose(fid); Find the root of the polynomial x3 - 2x - 5 using interval bisection: a = 0; fa = -Inf; b = 3; fb = Inf; while b-a > eps*b
x = (a+b)/2;
fx = x^3-2*x-5;
if fx == 0
break
elseif sign(fx) == sign(fa)
a = x; fa = fx;
else
b = x; fb = fx;
end
end
disp(x)



Take advantage of short-circuiting to avoid error or warning messages:
x = 42;
while exist('myfunction.m') && (myfunction(x) >= pi)
disp('Condition is true')
break
end




who -List variables in workspace
Syntax
who
who(variables)
who(location)
who(variables,location)
c = who(variables,location)
Description
who lists in alphabetical order all variables in the currently active workspace.
who(variables) lists only the specified variables.
who(location) lists variables in the specified location: 'global' for the global workspace, or '-file' for a MAT-file. For MAT-files, you must also include the file name as an input.
who(variables,location) lists the specified variables in the specified location. The location input can appear before or after variables.
c = who(variables,location) stores the names of the variables in cell array c. Specifying variables and location is optional.
Tips
 The who function displays the variable list unless you specify an output argument.
 When used within a nested function, the who function lists the variables in the workspaces of that function and all functions containing that function, grouped by workspace. This applies whether you call who from your function code or from the MATLAB debugger.
Input Arguments
variables Strings that specify the variables to list. Use one of these forms:
var1, var2, ... List the specified variables.
Use the '*' wildcard to match patterns. For example,who('A*') lists all variables that start with A.
'-regexp', expressions List variables whose names match the specified regular expressions.

Default: '*' (all variables)
location String that indicates whether to list variables from the global workspace or from a file:
'global' Global workspace.
'-file', filename MAT-file. The filename input can include the full, relative, or partial path.
Default: '' (current workspace)
Output Arguments
c Cell array of strings that correspond to each variable name.
Examples
Display information about variables in the current workspace whose names start with the letter a:
who a*



Show variables stored in MAT-file durer.mat:
who -file durer
This code returns:
Your variables are:

X caption map



Store the variable names from durer.mat in cell array durerInfo:
durerInfo = who('-file', 'durer');
Display the contents of cell array durerInfo:
for k=1:length(durerInfo)
disp(durerInfo{k})
end
This code returns:
X
caption
map



Suppose that a file mydata.mat contains variables with names that start with java and end with Array. Display information about those variables:
whos -file mydata -regexp \



Call who within a nested function (get_date):
function who_demo
date_time = datestr(now);

[str pos] = textscan(date_time, '%s%s%s', ...
1, 'delimiter', '- :');
get_date(str);

function get_date(d)
day = d{1};
mon = d{2};
year = d{3};
who
end

end
When you run who_demo, the who function displays the variables by function workspace (although the name of the function does not appear in the output):
Your variables are:

d mon ans pos
day year date_time str
Alternatives
To view the variables in the workspace, use the Workspace browser. To view the contents of MAT-files, use the Details Panel of the Current Folder Browser.


xlabel -Label x-axis
Alternatives
To control the presence and appearance of axis labels on a graph, use the Property Editor plotting tool . For details, see The Property Editor in the MATLAB Graphics documentation.
Syntax
xlabel('string')
xlabel(fname)
xlabel(...,'PropertyName',PropertyValue,...)
xlabel(axes_handle,...)
h = xlabel(...)
Description
Every axes graphics object can have one label for the x-axis. The label appears beneath its respective axis in a two-dimensional plot and to the side or beneath the axis in a three-dimensional plot.
xlabel('string') labels the x-axis of the current axes.
xlabel(fname) evaluates the function fname, which must return a string. Then it displays the string beside the x-axis.
xlabel(...,'PropertyName',PropertyValue,...) specifies property name-value pairs for the text graphics object created by xlabel.
xlabel(axes_handle,...) plots into the axes with handle axes_handle instead of the current axes (gca).
h = xlabel(...) returns the handle to the text object used as the label.
Tips
Reissuing xlabel command causes the new label to replace the old label.
For three-dimensional graphics, MATLAB puts the label in the front or on the side, so the plot does not hide it.
Examples
This example shows how to give a string as input to xlabel.
xlabel('Population');



Passing a numeric input as input to the function.
xlabel(123);



Passing a handle as input to xlabel.
h = figure;
xlabel(h);



This example displays the label in multiple lines.
xlabel({2010;'Population';'in Years'});



This example shows you how to use name-value pairs in xlabel.
xlabel('Population','fontsize',12,'fontweight','b','color','r');
When resizing the figure window, you may want to display graph to the scale or be able to see the text in title and labels completely. For more information about this, see Properties Controlling Axes Size.


ylabel -Label y-axis
Alternatives
To control the presence and appearance of axis labels on a graph, use the Property Editor plotting tool . For details, see The Property Editor in the MATLAB Graphics documentation.
Syntax
ylabel('string')
ylabel(fname)
ylabel(...,'PropertyName',PropertyValue,...)
ylabel(axes_handle,...)
h = ylabel(...)
Description
Every axes graphics object can have one label for the y-axis. The label appears beneath its respective axis in a two-dimensional plot and to the side or beneath the axis in a three-dimensional plot.
ylabel('string') labels the y-axis of the current axes.
ylabel(fname) evaluates the function fname, which must return a string. Then it displays the string beside the y-axis.
ylabel(...,'PropertyName',PropertyValue,...) specifies property name-value pairs for the text graphics object created by ylabel.
ylabel(axes_handle,...) plots into the axes with handle axes_handle instead of the current axes (gca).
h = ylabel(...) returns the handle to the text object used as the label.
Tips
Reissuing ylabel command causes the new label to replace the old label.
For three-dimensional graphics, MATLAB puts the label in the front or on the side, so that the plot does not hide it.
Examples
This example shows how to give a string as input to ylabel.
ylabel('Population');



Passing a numeric input as input to the function.
ylabel(123);



Passing a handle as input to ylabel.
h = figure;
ylabel(h);



This example displays the label in multiple lines.
ylabel({2010;'Population';'in Years'});



This example shows you how to use name-value pairs in ylabel.
ylabel('Population','fontsize',12,'fontweight','b','color','r');
When resizing the figure window, you may want to display graph to the scale or be able to see the text in title and labels completely. For more information about this, see Properties Controlling Axes Size.



zeros -Create array of all zeros
Syntax
B = zeros(n)
B = zeros(m,n)
B = zeros([m n])
B = zeros(m,n,p,...)
B = zeros([m n p ...])
B = zeros(size(A))
Y = zeros
zeros(m, n,...,classname)
zeros([m,n,...],classname)
Description
B = zeros(n) returns an n-by-n matrix of zeros. An error message appears if n is not a scalar.
B = zeros(m,n) or B = zeros([m n]) returns an m-by-n matrix of zeros.
B = zeros(m,n,p,...) or B = zeros([m n p ...]) returns an m-by-n-by-p-by-... array of zeros.
Note The size inputs m, n, p, ... should be nonnegative integers. Negative integers are treated as 0. If any trailing dimensions are 0, output Bdoes not include those dimensions.
B = zeros(size(A)) returns an array the same size as A consisting of all zeros.
Y = zeros with no arguments is the scalar 0.
zeros(m, n,...,classname) or zeros([m,n,...],classname) is an m-by-n-by-... array of zeros of data type classname. classname is a string specifying the data type of the output. classname can have the following values: 'double', 'single', 'int8', 'uint8', 'int16', 'uint16', 'int32','uint32', 'int64', or 'uint64'.
Examples
x = zeros(2,3,'int8');
Tips
The MATLAB language does not have a dimension statement; MATLAB automatically allocates storage for matrices. Nevertheless, for large matrices, MATLAB programs may execute faster if the zeros function is used to set aside storage for a matrix whose elements are to be generated one at a time, or a row or column at a time. For example
x = zeros(1,n);
for i = 1:n, x(i) = i; end

Tidak ada komentar:

Posting Komentar