Matlab知识总结

Matlab笔记

基础操作

1、基础命令

Cd+绝对路径     :改变当前目录

Pwd             :查看当前目录的绝对路径

doc addpath      :出现帮助菜单中关于addpath的知识

help addpath      :命令窗口出现addpath的介绍

lookfor           :关键词搜索命令,lookfor color   与color有关的函数

  注:搜索时有时会出现大量信息,按ctrl+C可终止搜索,或者在使用该命令前先输入more on来启动分屏显示功能,输入more off回车,可以关闭分屏显示功能。

What             :查看当前目录下的文件那些和matlab有关

What general       :列出matlab的基础函数名

Which             :可以很方便地给出某个函数的绝对路径

Demo 回车         :可以进入matlab自带的演示教程

home 回车        :将光标置于当前窗口的左上方

(1)Edit

Edit or create file

Alternatives

As an alternative to the edit function, select File > New or Open in the MATLAB desktop or any desktop tool.

Syntax

edit
edit fun.m
edit file.ext
edit fun1 fun2 fun3 ...
edit classname/fun
edit private/fun
edit classname/private/fun
edit +packagename/classname/fun
edit('my file.m')

Description

edit opens a new editor window.

edit fun.m opens the file fun.m in the default editor. The fun.m file specification can include a partial path, complete path, relative path, or no path. Be aware of the following:

If you do not specify a path, the current folder is the default.

If you specify a path, the folder must exist; otherwise MATLAB returns an error.

If you specify a path and the folder exits, but the specified file does not, a prompt opens such as shown in the following image:

To create a blank file named fun.m in the specified folder, click Yes. To suppress the prompt, select Do not show this prompt again. To reinstate the prompt after suppressing it, open the Preferences dialog box by selecting File > Preferences > General > Confirmation Dialogs and then selecting Prompt when editing files that do not exist in the pane on the right.

edit file.ext opens the specified file.

edit fun1 fun2 fun3 ... opens fun1.m, fun2.m, fun3.m, and so on, in the default editor.

edit classname/fun, or edit private/fun, or edit classname/private/fun opens a method, private function, or private method for the named class.

edit +packagename/classname/fun opens a method for the named class in the named package.

edit('my file.m') opens the file my file.m in the default editor. This form of the edit function is useful when a file name contains a space; you cannot use the command form in such a case.

2、命令输入的几个实用方法

a、利用tab按键

   输入命令的前几个字符,接着连按两下tab键,出现函数列表

b、利用键盘上的上下方向键,调出历史命令

c、当matlab按顺序执行很多命令时,可将要运行的大量命令统一存放在一个文本文件里,扩展名为.m,然后在命令窗口键入这个文件名,回车,matlab就会一次性地执行这些命令

3、matlab保留常数

Ans      eps:当前计算机的零阈值

i和f    :若i和f值不被改写,则它们代表虚数单位,使用前,应确定它们没有被改写。恢复变量:i=sqrt(-1)。

Inf       :无穷大,负无穷用-inf表示

NaN     :非数(not a number)

Nargin    :函数输入的变量的实际个数

Nargout   :函数输出变量的实际个数

Pi        :圆周率

4、变量命名规则

   首个字符必须是字母,并且后面字符不能包含空格、标点和括号。Matlab中大小写字符表示的含义不同

5、数据类型结构

   利用help datatype查看所有的数据类型基本类型

常用的:

数值型:双精度、浮点数,其matlab表示为double

逻辑型:只包含1,0。1为true,0为false

字符型:赋值时,字符串是用单引号括起来的

单元数据

>>clear all   %清除计算机内存所保存的变量和函数

>>who      %查看当前内存里的变量名

>>whos      %查看当前内存里变量的详细说明

>>clc        %清屏

注:命令行结尾加上一个分号表示不屏显结果,只运行命令。

矩阵

1、 基本规则

a、 矩阵元素必须在中括号内[]

b、 同行元素之间用空格或逗号隔开

c、 行与行之间可以用分号或回车隔开

d、 如果矩阵的某行过长,可以在续行符…后另起一行接着输入

2、 矩阵函数

Ones  :生成元素全为1的矩阵,ones(n)将生成n*n的矩阵

Zeros  :生成元素全为0的矩阵

Nan    :生成元素全为nan的矩阵

Rand   :生成在[0,1]区间均匀分布的随机矩阵

Randn  :生成均值为0,方差为1的标注正态分布随机矩阵

Eye    :生成单位矩阵,主对角线元素全为1

Linspace  :生成等间隔的行向量,其调用格式为:linspace(a,b,n),其中a和b是生成向量的第一个和最后一个元素,n是元素总数

Magic  :魔方矩阵

3、矩阵运算

+  -  *  /(右除)  \(左除)   ^(乘方)   ‘(转置)

a、点运算

  点运算符号有.*  ./    .\   .^

  两矩阵进行点运算是指对它们的对应元素进行相关运算,要求两个矩阵的维数相同

b、关系运算

  <  >=  >  <=  ==(等于)  ~=(不等于)

  运算规则

(1)当对象为两个标量,则直接比较大小关系,成立结果为1,否则为0

(2)当参与比较的是两个维数相同的矩阵时,比较是对两个矩阵相同位置的元素按标量关系运算规则逐个进行,结果为一个维数与原矩阵相同的矩阵,元素由0或1组成

(3)当一个是标量,一个是矩阵时,则把标量与矩阵的每一个元素按标量关系运算规则逐个比较,并给出一个维数与原矩阵相同的矩阵,由0或1组成

C、逻辑运算

&(与)    |(或)   ~(非)

d、冒号操作

>>b=-3:2    %生成间隔为1的向量

>>c=130:-2.4:115      %中间可以指定任意间隔

>>d=a(:,3)            %提取矩阵a的第3列元素,并转置后赋值给变量d

E、矩阵的维数

 >>a=

      1 2 3 4

      7 8 9 10

      3 4 6 9

      5 7 10 11

>>[s1,s2]=size(a)         %将矩阵a的每一维的长度赋值给s1和s2

   S1=4               s2=4

>>b1=length(b)     %向量b的长度      b=-3 -2 -1 0 1 2

  b1= 6

>>ndims(a)        %直接得到a的维数

  Ans=2

f、空矩阵的应用

空矩阵的表示[]

>>a(3,:)=[]            %删除矩阵a的第3行

h、矩阵的翻转

(1)利用撇号可以实现矩阵的行列互换

(2)>>fliplr(a)       %将矩阵a左右翻转,第一列变成最后一列,以此类推

  >>flipud(a)        %将矩阵a上下翻转,第一行变成最后一行,以此类推

  >>rot90(a)         %将矩阵a逆时针旋转90度

Rot90(a,k)  :将矩阵a逆时针旋转k倍的90度,k为1可省略

g、矩阵的拼接

>>b=[a  ones(3,6)*2;nan(size(a))  a-1]

k、基本函数操作

  help elfun和help matfun可以查看基本的数学函数和线性代数运算函数列表

>>sum(a)         %对矩阵a的每一列求和

>>sum(a(:));        %对矩阵a的全部元素求和     a(:)将矩阵a变成向量a

补充:

>>type +文件名      %查看当期文件目录下的内容

 利用mat文件可以将当前matlab工作空间中的一些有用的变量长久地保留下来,扩展名为.mat,mat文件生成和装入用save和load命令完成

 常用格式:

      Save 文件名[变量名表][-append][-ascii]

      load 文件名[变量名表][-ascii]

>>save  wps     %保存为wps.mat文件

>>ls

  wps.mat

>>load  wps    %装入mat文件

>>save  wps x y      %只保存x y变量

>>load  wps x       %  只装入x变量

>>help  tic/toc           %时间机器

取整函数:  fix floor ceil round

fix(1.2)=1      fix(2.3)=2         靠近0取整

floor(1.2)=1    floor(-1.2)=2      靠近负无穷取整

ceil(1.2)=2     ceil(-1.2)=-1       靠近正无穷取整

round(1.2)=1   round(1.6)=2      四舍五入

 a= [1 2 3;4 5 6]

>>a(end,end)

ans=6

>>a(end-1,end)

 ans=2

Matlab指令及函数总结

logical

  Convert numeric values to logical

Syntax

   K = logical(A)

K = logical(A) returns an array that can be used for logical indexing or logical tests.

Examples

Given A = [1 2 3; 4 5 6; 7 8 9], the statement B = logical(eye(3)) returns a logical array

B =

   1   0   0

   0   1   0

   0   0   1

which can be used in logical indexing that returns A's diagonal elements:

A(B)

ans =

     1

     5

     9

However, attempting to index into A using the numeric array eye(3) results in:

A(eye(3))

??? Subscript indices must either be real positive integers or

logicals.

ndims

Number of array dimensions

Syntax

n = ndims(A)

Description

n = ndims(A) returns the number of dimensions in the array A. The number of dimensions in an array is always greater than or equal to 2. Trailing singleton dimensions are ignored. A singleton dimension is any dimension for which size(A,dim) = 1.

Algorithms

ndims(x) is length(size(x)).

size

Array dimensions

Syntax

d = size(X)
[m,n] = size(X)
m = size(X,dim)
[d1,d2,d3,...,dn] = size(X),

Description

d = size(X) returns the sizes of each dimension of array X in a vector d with ndims(X) elements. If X is a scalar, which MATLAB software regards as a 1-by-1 array, size(X) returns the vector [1 1].

[m,n] = size(X) returns the size of matrix X in separate variables m and n.

m = size(X,dim) returns the size of the dimension of X specified by scalar dim.

[d1,d2,d3,...,dn] = size(X), for n > 1, returns the sizes of the dimensions of the array X in the variables d1,d2,d3,...,dn, provided the number of output arguments n equals ndims(X). If n does not equal ndims(X), the following exceptions hold:

Examples

Example 1

The size of the second dimension of rand(2,3,4) is 3.

m = size(rand(2,3,4),2)

m =

     3

Here the size is output as a single vector.

d = size(rand(2,3,4))

d =

     2     3     4

Here the size of each dimension is assigned to a separate variable.

[m,n,p] = size(rand(2,3,4))

m =

     2

n =

     3

p =

     4

Example 2

If X = ones(3,4,5), then

[d1,d2,d3] = size(X)

d1 =       d2 =       d3 =

     3          4          5

But when the number of output variables is less than ndims(X):

[d1,d2] = size(X)

d1 =       d2 =

     3          20

The "extra" dimensions are collapsed into a single product.

If n > ndims(X), the "extra" variables all represent singleton dimensions:

[d1,d2,d3,d4,d5,d6] = size(X)

d1 =       d2 =       d3 =

     3          4          5

d4 =       d5 =       d6 =

     1          1          1

length

Length of vector or largest array dimension

Syntax

numberOfElements = length(array)

Description

numberOfElements = length(array) finds the number of elements along the largest dimension of an array. array is an array of any MATLAB data type and any valid dimensions. numberOfElements is a whole number of the MATLAB double class.

For nonempty arrays, numberOfElements is equivalent to max(size(array)). For empty arrays, numberOfElements is zero.

Examples

Create a 1-by-8 array X and use length to find the number of elements in the second (largest) dimension:

X = [5, 3.4, 72, 28/4, 3.61, 17 94 89];

length(X)

ans =

     8

Create a 4-dimensional array Y in which the third dimension is the largest. Use length to find the number of elements in that dimension:

Y = rand(2, 5, 17, 13);

length(Y)

ans =

    17

Create a struct array S with character and numeric fields of different lengths. Use the structfun function to apply length to each field of S:

S = struct('f1', 'Name:', 'f2', 'Charlie', ...

           'f3', 'DOB:', 'f4', 1917)

S =

    f1: 'Name:'

    f2: 'Charlie'

    f3: 'DOB:'

    f4: 1917

structfun(@(field)length(field), S)

ans =

     5

     7

     4

     1

☆numel

Number of elements in array or subscripted array expression

Syntax

n = numel(A)
n = numel(A, index1, index2, ... indexn)

Description

n = numel(A) returns the number of elements, n, in array A.

n = numel(A, index1, index2, ... indexn) returns the number of subscripted elements, n, in A(index1, index2, ..., indexn). To handle the variable number of arguments, numel is typically written with the header function n = numel(A, varargin), where varargin is a cell array with elements index1, index2, ... indexn.

The MATLAB software implicitly calls the numel built-in function whenever an expression generates a comma-separated list. This includes brace indexing (i.e., A{index1,index2,...,indexN}), and dot indexing (i.e., A.fieldname).

Tips

It is important to note the significance of numel with regards to the overloaded subsref and subsasgn functions. In the case of the overloaded subsref function for brace and dot indexing (as described in the last paragraph), numel is used to compute the number of expected outputs (nargout) returned from subsref. For the overloaded subsasgn function, numel is used to compute the number of expected inputs (nargin) to be assigned using subsasgn. The nargin value for the overloaded subsasgn function is the value returned by numel plus 2 (one for the variable being assigned to, and one for the structure array of subscripts).

As a class designer, you must ensure that the value of n returned by the built-in numel function is consistent with the class design for that object. If n is different from either the nargout for the overloaded subsref function or the nargin for the overloaded subsasgn function, then you need to overload numel to return a value of n that is consistent with the class' subsref and subsasgn functions. Otherwise, MATLAB produces errors when calling these functions.

Examples

Create a 4-by-4-by-2 matrix. numel counts 32 elements in the matrix.

a = magic(4);

a(:,:,2) = a'

a(:,:,1) =

    16     2     3    13

     5    11    10     8

     9     7     6    12

     4    14    15     1

a(:,:,2) =

    16     5     9     4

     2    11     7    14

     3    10     6    15

    13     8    12     1

numel(a)

ans =

    32

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 equals prod(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

permute

Rearrange dimensions of N-D array

Syntax

B = permute(A,order)

Description

B = permute(A,order) rearranges the dimensions of A so that they are in the order specified by the vector order. B has the same values of A but the order of the subscripts needed to access any particular element is rearranged as specified by order. All the elements of order must be unique.

Tips

permute and ipermute are a generalization of transpose (.') for multidimensional arrays.

Examples

Given any matrix A, the statement

permute(A,[2 1])

is the same as A.'.

For example:

A = [1 2; 3 4]; permute(A,[2 1])

ans =

     1     3

     2     4

The following code permutes a three-dimensional array:

X = rand(12,13,14);

Y = permute(X,[2 3 1]);

size(Y)

ans =

    13    14    12

repmat

Replicate and tile array

Syntax

B = repmat(A,m,n)
B = repmat(A,[m n])
B = repmat(A,[m n p...])

Description

B = repmat(A,m,n) creates a large matrix B consisting of an m-by-n tiling of copies of A. The size of B is [size(A,1)*m, (size(A,2)*n]. The statement repmat(A,n) creates an n-by-n tiling.

B = repmat(A,[m n]) accomplishes the same result as repmat(A,m,n).

B = repmat(A,[m n p...]) produces a multidimensional array B composed of copies of A. The size of B is [size(A,1)*m, size(A,2)*n, size(A,3)*p, ...].

Tips

repmat(A,m,n), when A is a scalar, produces an m-by-n matrix filled with A's value and having A's class. For certain values, you can achieve the same results using other functions, as shown by the following examples:

repmat(NaN,m,n) returns the same result as NaN(m,n).

repmat(single(inf),m,n) is the same as inf(m,n,'single').

repmat(int8(0),m,n) is the same as zeros(m,n,'int8').

repmat(uint32(1),m,n) is the same as ones(m,n,'uint32').

repmat(eps,m,n) is the same as eps(ones(m,n)).

Examples

Example 1

In this example, repmat replicates 12 copies of the second-order identity matrix, resulting in a "checkerboard" pattern.

B = repmat(eye(2),3,4)

B =

     1     0     1     0     1     0     1     0

     0     1     0     1     0     1     0     1

     1     0     1     0     1     0     1     0

     0     1     0     1     0     1     0     1

     1     0     1     0     1     0     1     0

     0     1     0     1     0     1     0     1

The statement N = repmat(NaN,[2 3]) creates a 2-by-3 matrix of NaNs.

Example 2

If you have code that uses repmat and also a binary operator or function, you can transform the code to use the bsxfun function instead. In certain cases, this can provide a simpler and faster solution.

This example replaces the sum of two repmat operations with a single call to bsxfun:

x = 1:5; y = (1:10)';

% Replace this code

repmat(x,10,1) + repmat(y,1,5)

% with the following:

bsxfun(@plus, x, y)

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

cell

Create cell array

Syntax

C = cell(dim)
C = cell(dim1,...,dimN)
D = cell(obj)

Description

C = cell(dim) creates a cell array of empty matrices. If dim is a scalar, C is dim-by-dim. If dim is a vector, C is dim(1)-by-...-dim(N), where N is the number of elements of dim.

C = cell(dim1,...,dimN) creates cell array C, where C is dim1-by-...-dimN.

D = cell(obj) converts a Java array or .NET array of System.String or System.Object into a MATLAB cell array.

Tips

Creating an empty array with the cell function, such as

C = cell(3,4,2);

is exactly equivalent to assigning an empty array to the last index of a new cell array:

C{3,4,2} = [];

Input Arguments

Output Arguments

Examples

Create an empty 3-by-4-by-2 cell array.

mycell = cell(3,4,2);

Create a cell array that is the same size as mycell, created in the previous example.

similar = cell(size(mycell));

Convert an array of java.lang.String objects into a MATLAB cell array.

strArray = java_array('java.lang.String', 3);

strArray(1) = java.lang.String('one');

strArray(2) = java.lang.String('two');

strArray(3) = java.lang.String('three');

cellArray = cell(strArray)

This code returns

cellArray =

    'one'

    'two'

    'three'

Create a cell array of folders in the c:\work folder, using the .NET Framework System.IO.Directory class :

myList = cell(System.IO.Directory.GetDirectories('c:\work'));

celldisp(myList)

num2cell

Convert array to cell array with consistently sized cells

Syntax

C = num2cell(A)
C = num2cell(A,dim)
C = num2cell(A,[dim1,...,dimN])

Description

C = num2cell(A) converts array A into cell array C by placing each element of A into a separate cell in C.

C = num2cell(A,dim) creates vectors in cells of C that contain elements from the specified dimension dim of A.

C = num2cell(A,[dim1,...,dimN]) creates arrays in cells of C that contain elements from the specified dimensions of A.

Examples

To run the examples in this section, first create a three-dimensional numeric array.

a = reshape(1:12,4,3)';

a(:,:,2) = a * 10

a is 3-by-4-by-2 array:

a(:,:,1) =

     1     2     3     4

     5     6     7     8

     9    10    11    12

a(:,:,2) =

    10    20    30    40

    50    60    70    80

    90   100   110   120

Convert numeric array a (created in the previous example) to a cell array with the same dimensions.

c = num2cell(a);

c is a 3-by-4-by-2 cell array, where each cell contains a scalar numeric value:

c(:,:,1) =

    [1]    [ 2]    [ 3]    [ 4]

    [5]    [ 6]    [ 7]    [ 8]

    [9]    [10]    [11]    [12]

c(:,:,2) =

    [10]    [ 20]    [ 30]    [ 40]

    [50]    [ 60]    [ 70]    [ 80]

    [90]    [100]    [110]    [120]

Combine the elements from the first dimension of array a (created in a previous example) into vectors within cells of cell array c2.

c2 = num2cell(a, 1)

Each cell of c2 contains a 3-by-1 vector:

c2(:,:,1) =

    [3x1 double]    [3x1 double]    [3x1 double]    [3x1 double]

c2(:,:,2) =

    [3x1 double]    [3x1 double]    [3x1 double]    [3x1 double]

where, for example, c2{1} returns

ans =

     1

     5

     9

Combine the elements in the first and second dimensions of array a (created in a previous example) into arrays within cells of cell array c3.

c3 = num2cell(a, [1, 2])

Each cell of c3 contains a 3-by-4 numeric array:

c3(:,:,1) =

    [3x4 double]

c3(:,:,2) =

    [3x4 double]

where, for example, c3{1} returns

ans =

     1     2     3     4

     5     6     7     8

     9    10    11    12

cell2mat

Convert cell array to numeric array

Syntax

A= cell2mat(C)

Description

A= cell2mat(C) converts cell array C with contents of the same data type into a single array, A.

Input Arguments

Output Arguments

Examples

Combine matrices in the four cells of cell array c into matrix m.

c = {[1],    [2, 3, 4];

     [5; 9], [6, 7, 8; 10, 11, 12]};

m = cell2mat(c)

m is a 3-by-4 matrix:

m =

     1     2     3     4

     5     6     7     8

     9    10    11    12

mat2cell

Convert array to cell array with potentially different sized cells

Syntax

C = mat2cell(A,dim1Dist,...,dimNDist)
C = mat2cell(A,rowDist)

Description

C = mat2cell(A,dim1Dist,...,dimNDist) divides array A into smaller arrays within cell array C. Vectors dim1Dist,...dimNDist specify how to divide the rows, columns, and (when applicable) higher dimensions of A.

C = mat2cell(A,rowDist) divides array A into an n-by-1 cell array C, where n == numel(rowDist).

Input Arguments

Output Arguments

Examples

Divide the 5-by-4 matrix X into 2-by-3 and 2-by-2 matrices contained in a cell array.

X = reshape(1:20,5,4)'

C = mat2cell(X, [2 2], [3 2])

celldisp(C)

This code returns

X =

     1     2     3     4     5

     6     7     8     9    10

    11    12    13    14    15

    16    17    18    19    20

C =

    [2x3 double]    [2x2 double]

    [2x3 double]    [2x2 double]

C{1,1} =

     1     2     3

     6     7     8

C{2,1} =

    11    12    13

    16    17    18

C{1,2} =

     4     5

     9    10

C{2,2} =

    14    15

    19    20

Divide X (created in the previous example) into a 2-by-1 cell array.

C = mat2cell(X, [1 3])

celldisp(C)

This code returns

C =

    [1x5 double]

    [3x5 double]

C{1} =

     1     2     3     4     5

C{2} =

     6     7     8     9    10

    11    12    13    14    15

    16    17    18    19    20

struct

Create structure array

Syntax

s = struct('field1', values1, 'field2', values2, ...)
s = struct('field1', {}, 'field2', {}, ...)
s = struct
s = struct([])
s = struct(obj)

Description

s = struct('field1', values1, 'field2', values2, ...) creates a structure array with the specified fields and values. Each value input (values1, values2, etc.), can either be a cell array or a scalar value. Those that are cell arrays must all have the same dimensions.

The size of the resulting structure is the same size as the value cell arrays, or 1-by-1 if none of the values is a cell array. Elements of the value array inputs are placed into corresponding structure array elements.

Structure field names must begin with a letter, and are case-sensitive. The rest of the name may contain letters, numerals, and underscore characters. Use the namelengthmax function to determine the maximum length of a field name.

s = struct('field1', {}, 'field2', {}, ...) creates an empty structure with fields field1, field2, ...

s = struct creates a 1-by-1 structure with no fields.

s = struct([]) creates an empty structure with no fields.

s = struct(obj) creates a structure s that is identical to the underlying structure in the input object obj. MATLAB does not convert obj, but rather creates s as a new structure. This structure does not retain the class information in obj.

Tips

Two Ways to Access Fields

The most common way to access the data in a structure is by specifying the name of the field that you want to reference. Another means of accessing structure data is to use dynamic field names. These names express the field as a variable expression that MATLAB evaluates at run-time.

Fields That Are Cell Arrays

To create fields that contain cell arrays, place the cell arrays within a value cell array. For instance, to create a 1-by-1 structure, type

s = struct('strings',{{'hello','yes'}},'lengths',[5 3])

s =

   strings: {'hello'  'yes'}

   lengths: [5 3]

Specifying Cell Versus Noncell Values

When using the syntax

s = struct('field1', values1, 'field2', values2, ...)

the values inputs can be cell arrays or scalar values. For those values that are specified as a cell array, MATLAB assigns each element of values{m,n,...} to the corresponding field in each element of structure s:

s(m,n,...).fieldN = valuesN{m,n,...}

For those values that are scalar, MATLAB assigns that single value to the corresponding field for all elements of structure s:

s(m,n,...).fieldN = valuesN

See Example 3, below.

Examples

Example 1

The command

s = struct('type', {'big','little'}, 'color', {'red'}, ...

    'x', {3 4})

produces a structure array s:

s =

1x2 struct array with fields:

    type

    color

    x

The value arrays have been distributed among the fields of s:

s(1)

ans =

       type: 'big'

     color: 'red'

         x: 3

s(2)

ans =

       type: 'little'

     color: 'red'

         x: 4

Example 2

Similarly, the command

a.b = struct('z', {});

produces an empty structure a.b with field z.

a.b

ans =

      0x0 struct array with fields:

          z

Example 3

This example initializes one field f1 using a cell array, and the other f2 using a scalar value:

s = struct('f1', {1 3; 2 4}, 'f2', 25)

s =

2x2 struct array with fields:

    f1

    f2

Field f1 in each element of s is assigned the corresponding value from the cell array {1 3; 2 4}:

s.f1

ans =

     1

ans =

     2

ans =

     3

ans =

     4

Field f2 for all elements of s is assigned one common value because the values input for this field was specified as a scalar:

s.f2

ans =

    25

ans =

    25

ans =

    25

ans =

    25

补充:

date     %显示当前系统日期,结果为一个字符串

y=year(now);m=month(now);d=day(now)    %分别提取当前系统日期

y=year(now) m=month(now) d=day(now)    %分别提取当前系统日期

y=year(now); m=month(now); d=day(now);    %分别提取当前系统日期

n=datenum(1924,10,24,10,30,0)    %1924年10月24日10点30分距原点(0000年1月1日)的天数

datestr(n+43210.12)    %上边时间的43210.12天后的日期

leapyear([1986 20## 2024])     %判断是否为闰年,结果为逻辑值

tic;a=1:100;b=sqrt(a);toc;         %计算中间代码的运行时间

home    %将光标停留在当前窗口的左上角

pause(2)    %暂停2秒,如果没有参数,则需要按任意键继续

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'))

lower

Convert string to lowercase

Syntax

t = lower('str')
B = lower(A)

Description

t = lower('str') returns the string formed by converting any uppercase characters in str to the corresponding lowercase characters and leaving all other characters unchanged.

B = lower(A) when A is a cell array of strings, returns a cell array the same size as A containing the result of applying lower to each string within A.

Examples

lower('MathWorks') is mathworks.

upper

Convert string to uppercase

Syntax

t = upper('str')
B = upper(A)

Description

t = upper('str') converts any lowercase characters in the string str to the corresponding uppercase characters and leaves all other characters unchanged.

B = upper(A) when A is a cell array of strings, returns a cell array the same size as A containing the result of applying upper to each string within A.

Examples

upper('attention!') is ATTENTION!.

peaks

Example function of two variables Syntax

Z = peaks;

Z = peaks(n);

Z = peaks(V);

Z = peaks(X,Y);

peaks;

peaks(N);

peaks(V);

peaks(X,Y);

[X,Y,Z] = peaks;

[X,Y,Z] = peaks(n);

[X,Y,Z] = peaks(V);

Description

peaks is a function of two variables, obtained by translating and scaling Gaussian distributions, which is useful for demonstrating mesh, surf, pcolor, contour, and so on.

Z = peaks; returns a 49-by-49 matrix.

Z = peaks(n); returns an n-by-n matrix.

Z = peaks(V); returns an n-by-n matrix, where n = length(V).

Z = peaks(X,Y); evaluates peaks at the given X and Y (which must be the same size) and returns a matrix the same size.

peaks(...) (with no output argument) plots the peaks function with surf.

[X,Y,Z] = peaks(...); returns two additional matrices, X and Y, for parametric plots, for example, surf(X,Y,Z,del2(Z)). If not given as input, the underlying matrices X and Y are

[X,Y] = meshgrid(V,V)

where V is a given vector, or V is a vector of length n with elements equally spaced from -3 to 3. If no input argument is given, the default n is 49.

meshgrid

Rectangular grid in 2-D and 3-D space

Syntax

[X,Y] = meshgrid(xgv,ygv)
[X,Y,Z] = meshgrid(xgv,ygv,zgv)
[X,Y] = meshgrid(gv)
[X,Y,Z] = meshgrid(gv)

Description

[X,Y] = meshgrid(xgv,ygv) replicates the grid vectors xgv and ygv to produce a full grid. This grid is represented by the output coordinate arrays X and Y. The output coordinate arrays X and Y contain copies of the grid vectors xgv and ygv respectively. The sizes of the output arrays are determined by the length of the grid vectors. For grid vectors xgv and ygv of length M and N respectively, X and Y will have N rows and M columns.

[X,Y,Z] = meshgrid(xgv,ygv,zgv) produces three-dimensional coordinate arrays. The output coordinate arrays X, Y, and Z contain copies of the grid vectors xgv, ygv, and zgv respectively. The sizes of the output arrays are determined by the length of the grid vectors. For grid vectors xgv, ygv, and zgv of length M, N, and P respectively, X, Y, and Z will have N rows, M columns, and P pages.

[X,Y] = meshgrid(gv) is the same as [X,Y] = meshgrid(gv,gv). In other words, you can reuse the same grid vector in each respective dimension. The dimensionality of the output arrays is determined by the number of output arguments.

[X,Y,Z] = meshgrid(gv) is the same as [X,Y,Z] = meshgrid(gv,gv,gv). Again, the dimensionality of the output arrays is determined by the number of output arguments.

The output coordinate arrays are typically used to evaluate functions of two or three variables. They are also frequently used to create surface and volumetric plots.

Examples

Create a full grid from two monotonically increasing grid vectors:

[X,Y] = meshgrid(1:3,10:14)

X =

     1     2     3

     1     2     3

     1     2     3

     1     2     3

     1     2     3

Y =

    10    10    10

    11    11    11

    12    12    12

    13    13    13

    14    14    14

Use meshgrid to create a 3-D surface plot of a function:

[X,Y] = meshgrid(-2:.2:2, -2:.2:2);                               

Z = X .* exp(-X.^2 - Y.^2);                                       

surf(X,Y,Z)

ndgrid

Rectangular grid in N-D space

Syntax

[X1,X2,X3,...,Xn] = ndgrid(x1gv,x2gv,x3gv,...,xngv)
[X1,X2,...,Xn] = ndgrid(xgv)

Description

[X1,X2,X3,...,Xn] = ndgrid(x1gv,x2gv,x3gv,...,xngv) replicates the grid vectors x1gv,x2gv,x3gv,...,xngv to produce a full grid. This grid is represented by the output coordinate arrays X1,X2,X3,...,Xn. The ith dimension of any output array Xi contains copies of the grid vector xigv.

[X1,X2,...,Xn] = ndgrid(xgv) is the same as [X1,X2,...,Xn] = ndgrid(xgv,xgv,...,xgv). In other words, you can reuse the same grid vector in each respective dimension. The dimensionality of the output arrays is determined by the number of output arguments.

The coordinate arrays [X1,X2,X3,...,Xn] are typically used to evaluate functions of several variables and to create surface and volumetric plots.

Evaluate the function over the range ?2 < x1 < 2,?2 < x2 < 2:

[X1,X2] = ndgrid(-2:.2:2, -2:.2:2);

Z = X1 .* exp(-X1.^2 - X2.^2);

mesh(X1,X2,Z)

figure

Create figure graphics object

Syntax

figure
figure('PropertyName',propertyvalue,...)
figure(h)
h = figure(...)

Description

figure creates figure graphics objects. Figure objects are the individual windows on the screen in which the MATLAB software displays graphical output.

figure creates a new figure object using default property values. This automatically becomes the current figure and raises it above all other figures on the screen until a new figure is either created or called.

figure('PropertyName',propertyvalue,...) creates a new figure object using the values of the properties specified. For a description of the properties, see Figure Properties. MATLAB uses default values for any properties that you do not explicitly define as arguments.

figure(h) does one of two things, depending on whether or not a figure with handle h exists. If h is the handle to an existing figure, figure(h) makes the figure identified by h the current figure, makes it visible, and raises it above all other figures on the screen. The current figure is the target for graphics output. If h is not the handle to an existing figure, but is an integer, figure(h) creates a figure and assigns it the handle h. figure(h) where h is not the handle to a figure, and is not an integer, is an error.

h = figure(...) returns the handle to the figure object.

subplot

Create axes in tiled positions

Syntax

h = subplot(m,n,p) or subplot(mnp)
subplot(m,n,p,'replace')
subplot(m,n,P)
subplot(h)
subplot('Position',[left bottom width height])
subplot(..., prop1, value1, prop2, value2, ...)
h = subplot(...)

Description

subplot divides the current figure into rectangular panes that are numbered rowwise. Each pane contains an axes object which you can manipulate using Axes Properties. Subsequent plots are output to the current pane.

h = subplot(m,n,p) or subplot(mnp) breaks the figure window into an m-by-n grid and creates an axes object in the pth location for the current plot, and returns the axes handle. The axes are counted along the top row of the figure window, then the second row, etc. For example,

subplot(2,1,1), plot(income)

subplot(2,1,2), plot(outgo)

plots income on the top half of the window and outgo on the bottom half. If the CurrentAxes is nested in a uipanel, the panel is used as the parent for the subplot instead of the current figure. The new axes object becomes the current axes.

subplot(m,n,p,'replace') If the specified axes object already exists, delete it and create a new axes.

subplot(m,n,P), where P is a vector, specifies an axes position that covers all the subplot positions listed in P, including those spanned by P. For example, subplot(2,3,[2 5]) creates one axes spanning positions 2 and 5 only (because there are no intervening locations in the grid), while subplot(2,3,[2 6]) creates one axes spanning positions 2, 3, 5, and 6.

subplot(h) makes the axes object with handle h current for subsequent plotting commands.

subplot('Position',[left bottom width height]) creates an axes at the position specified by a four-element vector. left, bottom, width, and height are in normalized coordinates in the range from 0.0 to 1.0.

subplot(..., prop1, value1, prop2, value2, ...) sets the specified property-value pairs on the subplot axes object. Available property/value pairs are described more fully in Axes Properties. To add the subplot to a specific figure or uipanel, pass the handle as the value for the Parent property. You cannot specify both a Parent and a Position; that is, subplot('Position',[left bottom width height], 'Parent',h) is not a valid syntax.

h = subplot(...) returns the handle to the new axes object.

Examples

Upper and Lower Subplots with Titles

To plot income in the top half of a figure and outgo in the bottom half,

income = [3.2,4.1,5.0,5.6];

outgo = [2.5,4.0,3.35,4.9];

subplot(2,1,1); plot(income)

title('Income')

subplot(2,1,2); plot(outgo)

title('Outgo')

Subplots in Quadrants

The following illustration shows four subplot regions and indicates the command used to create each.

figure

subplot(2,2,1)

text(.5,.5,{'subplot(2,2,1)';'or subplot 221'},...

    'FontSize',14,'HorizontalAlignment','center')

subplot(2,2,2)

text(.5,.5,{'subplot(2,2,2)';'or subplot 222'},...

    'FontSize',14,'HorizontalAlignment','center')

subplot(2,2,3)

text(.5,.5,{'subplot(2,2,3)';'or subplot 223'},...

    'FontSize',14,'HorizontalAlignment','center')

subplot(2,2,4)

text(.5,.5,{'subplot(2,2,4)';'or subplot 224'},...

    'FontSize',14,'HorizontalAlignment','center'

Asymmetrical Subplots

The following combinations produce asymmetrical arrangements of subplots.

figure

subplot(2,2,[1 3])

text(.5,.5,'subplot(2,2,[1 3])',...

    'FontSize',14,'HorizontalAlignment','center')

subplot(2,2,2)

text(.5,.5,'subplot(2,2,2)',...

    'FontSize',14,'HorizontalAlignment','center')

subplot(2,2,4)

text(.5,.5,'subplot(2,2,4)',...

    'FontSize',14,'HorizontalAlignment','center')

You can also use the colon operator to specify multiple locations if they are in sequence.

figure

subplot(2,2,1:2)

text(.5,.5,'subplot(2,2,1:2)',...

    'FontSize',14,'HorizontalAlignment','center')

subplot(2,2,3)

text(.5,.5,'subplot(2,2,3)',...

    'FontSize',14,'HorizontalAlignment','center')

subplot(2,2,4)

text(.5,.5,'subplot(2,2,4)',...

    'FontSize',14,'HorizontalAlignment','center')

gca

Current axes handle

Syntax

h = gca

Description

h = gca returns the handle to the current axes for the current figure. If no axes exists, the MATLAB software creates one and returns its handle. You can use the statement

get(gcf,'CurrentAxes')

if you do not want MATLAB to create an axes if one does not already exist.

Current Axes

The current axes is the target for graphics output when you create axes children. The current axes is typically the last axes used for plotting or the last axes clicked on by the mouse. Graphics commands such as plot, text, and surf draw their results in the current axes. Changing the current figure also changes the current axes.

gcf

Current figure handle

Syntax

h = gcf

Description

h = gcf returns the handle of the current figure. The current figure is the figure window in which graphics commands such as plot, title, and surf draw their results. If no figure exists, the MATLAB software creates one and returns its handle. You can use the statement

get(0,'CurrentFigure')

if you do not want MATLAB to create a figure if one does not already exist.

hold

Retain current graph in figure

Syntax

hold on
hold off
hold all
hold
hold(axes_handle,...)

Description

The hold function determines whether new graphics objects are added to the graph or replace objects in the graph. hold toggles the NextPlot property between the add and replace states.

hold on retains the current plot and certain axes properties so that subsequent graphing commands add to the existing graph. If no current axes exist before you call hold on, MATLAB creates new axes and retains the default properties. However, some axes properties change to accommodate additional graphics objects. For example, the axes' limits increase when the data requires them to do so. hold on sets the NextPlot property of the current figure and axes to add.

hold off resets axes properties to their defaults before drawing new plots. hold off is the default. hold off sets the NextPlot property of the current axes to replace.

hold all holds the plot and the current line color and line style so that subsequent plotting commands do not reset the ColorOrder and LineStyleOrder property values to the beginning of the list. Plotting commands continue cycling through the predefined colors and linestyles from where the last plot stopped in the list.

hold toggles the hold state between adding to the graph and replacing the graph.

hold(axes_handle,...) applies the hold to the axes identified by the handle axes_handle. The hold function sets the NextPlot property of the current figure and the current axes. If several axes objects exist in a figure window, each axes has its own hold state. hold also creates an axes if one does not exist.

Test the hold state using the ishold function.

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 z data. 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 the XLimMode, 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 if PlotBoxAspectRatioMode 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.

axes

Create axes graphics object

Syntax

axes
axes('PropertyName',propertyvalue,...)
axes(h)
h = axes(...)

colormap

Set and get current colormap

Syntax

colormap(map)
colormap('default')
cmap = colormap
colormap(ax,...)

autumn varies smoothly from red, through orange, to yellow.

bone is a grayscale colormap with a higher value for the blue component. This colormap is useful for adding an "electronic" look to grayscale images.

colorcube contains as many regularly spaced colors in RGB color space as possible, while attempting to provide more steps of gray, pure red, pure green, and pure blue.

cool consists of colors that are shades of cyan and magenta. It varies smoothly from cyan to magenta.

copper varies smoothly from black to bright copper.

flag consists of the colors red, white, blue, and black. This colormap completely changes color with each index increment.

gray returns a linear grayscale colormap.

hot varies smoothly from black through shades of red, orange, and yellow, to white.

hsv varies the hue component of the hue-saturation-value color model. The colors begin with red, pass through yellow, green, cyan, blue, magenta, and return to red. The colormap is particularly appropriate for displaying periodic functions. hsv(m) is the same as hsv2rgb([h ones(m,2)]) where h is the linear ramp, h = (0:m–1)'/m.

jet ranges from blue to red, and passes through the colors cyan, yellow, and orange. It is a variation of the hsv colormap. The jet colormap is associated with an astrophysical fluid jet simulation from the National Center for Supercomputer Applications. See Examples.

lines produces a colormap of colors specified by the axes ColorOrder property and a shade of gray.

pink contains pastel shades of pink. The pink colormap provides sepia tone colorization of grayscale photographs.

prism repeats the six colors red, orange, yellow, green, blue, and violet.

spring consists of colors that are shades of magenta and yellow.

summer consists of colors that are shades of green and yellow.

white is an all white monochrome colormap.

winter consists of colors that are shades of blue and green.

Examples

The rgbplot function plots colormap values. Try rgbplot(hsv), rgbplot(gray), and rgbplot(hot).

The following commands display the flujet data using the jet colormap:

load flujet

image(X)

colormap(jet)

caxis

Color axis scaling

Syntax

caxis([cmin cmax])
caxis auto
caxis manual
caxis(caxis) freeze
v = caxis
caxis(axes_handle,...)

Description

caxis controls the mapping of data values to the colormap. It affects any surfaces, patches, and images with indexed CData and CDataMapping set to scaled. It does not affect surfaces, patches, or images with true color CData or with CDataMapping set to direct.

caxis([cmin cmax]) sets the color limits to specified minimum and maximum values. Data values less than cmin or greater than cmax map to cmin and cmax, respectively. Values between cmin and cmax linearly map to the current colormap.

caxis auto computes the color limits automatically using the minimum and maximum data values. This is the default behavior. Color values set to Inf map to the maximum color, and values set to -Inf map to the minimum color. Faces or edges with color values set to NaN are not drawn.

caxis manual and caxis(caxis) freeze the color axis scaling at the current limits. This enables subsequent plots to use the same limits when hold is on.

v = caxis returns a two-element row vector containing the [cmin cmax] currently in use.

caxis(axes_handle,...) uses the axes specified by axes_handle instead of the current axes.

caxis changes the CLim and CLimMode properties of axes graphics objects.

Tips

How Color Axis Scaling Works

Surface, patch, and image graphics objects having indexed CData and CDataMapping set to scaled map CData values to colors in the figure colormap each time they render. CData values equal to or less than cmin map to the first color value in the colormap, and CData values equal to or greater than cmax map to the last color value in the colormap. The following linear transformation is performed on the intermediate values (referred to as C below) to map them to an entry in the colormap (whose length is m, and whose row index is referred to as index below).

index = fix((C-cmin)/(cmax-cmin)*m)+1;

%Clamp values outside the range [1 m]

index(index<1) = 1;

index(index>m) = m;

Examples

Create (X,Y,Z) data for a sphere and view the data as a surface.

[X,Y,Z] = sphere;

C = Z;

surf(X,Y,Z,C)

Values of C have the range [-1 1]. Values of C near -1 are assigned the lowest values in the colormap; values of C near 1 are assigned the highest values in the colormap.

To map the top half of the surface to the highest value in the color table, use

caxis([-1 0])

To use only the bottom half of the color table, enter

caxis([-1 3])

which maps the lowest CData values to the bottom of the colormap, and the highest values to the middle of the colormap (by specifying a cmax whose value is equal to cmin plus twice the range of the CData).

The command

caxis auto

resets axis scaling back to autoranging and you see all the colors in the surface. In this case, entering

caxis

returns

[-1 1]

Using caxis with Image Data

Adjusting the color axis can be useful when using images with scaled color data. For example, load the image data and colormap for Cape Cod, Massachusetts. This command loads the image's data X and the image's colormap map into the workspace.

load cape

% Display the image with CDataMapping set to scaled and

%  install the image's colormap.

image(X,'CDataMapping','scaled')

colormap(map)

% This adjusts the color limits to span the range

% of the image data, which is 1 to 192:

caxis

ans =

     1   192

set

Set Handle Graphics object properties

Syntax

set(H,'PropertyName',PropertyValue,...)
set(H,a)
set(H,pn,pv,...)
set(H,pn,MxN_pv)
a = set(h)
pv = set(h,'PropertyName')

Description

set(H,'PropertyName',PropertyValue,...) sets the named properties to the specified values on the object(s) identified by H. H can be a vector of handles, in which case set sets the properties' values for all the objects.

set(H,a) sets the named properties to the specified values on the object(s) identified by H. a is a structure array whose field names are the object property names and whose field values are the values of the corresponding properties.

set(H,pn,pv,...) sets the named properties specified in the cell array pn to the corresponding value in the cell array pv for all objects identified in H.

set(H,pn,MxN_pv) sets n property values on each of m graphics objects, where m = length(H) and n is equal to the number of property names contained in the cell array pn. This allows you to set a given group of properties to different values on each object.

a = set(h) returns the user-settable properties and possible values for the object identified by h. a is a structure array whose field names are the object's property names and whose field values are the possible values of the corresponding properties. If you do not specify an output argument, the MATLAB software displays the information on the screen. h must be scalar.

pv = set(h,'PropertyName') returns the possible values for the named property. If the possible values are strings, set returns each in a cell of the cell array pv. For other properties, set returns a statement indicating that PropertyName does not have a fixed set of property values. If you do not specify an output argument, MATLAB displays the information on the screen. h must be scalar.

Examples

Set the Color property of the current axes to blue.

axes;

set(gca,'Color','b')

Change all the lines in a plot to black.

plot(peaks)

set(findobj('Type','line'),'Color','k')

get

Query Handle Graphics object properties

Syntax

get(h)
get(h,'PropertyName')
<m-by-n value cell array> = get(H,pn)
a = get(h)
a = get(0)
a = get(0,'Factory')
a = get(0,'FactoryObjectTypePropertyName')
a = get(h,'Default')
a = get(h,'DefaultObjectTypePropertyName')

Description

get(h) returns all properties of the graphics object identified by the handle h and their current values. For this syntax, h must be a scalar.

get(h,'PropertyName') returns the value of the property 'PropertyName' of the graphics object identified by h.

<m-by-n value cell array> = get(H,pn) returns n property values for m graphics objects in the m-by-n cell array, where m = length(H) and n is equal to the number of property names contained in pn.

a = get(h) returns a structure whose field names are the object's property names and whose values are the current values of the corresponding properties. If you do not specify an output argument, MATLAB displays the information on the screen. For this syntax, h may be a scalar or a m-by-n array of handles. If h is a vector, a will be a (m*n)-by-1 struct array.

a = get(0) returns the current values of all user-settable properties. a is a structure array whose field names are the object property names and whose field values are the values of the corresponding properties. If you do not specify an output argument, MATLAB displays the information on the screen.

a = get(0,'Factory') returns the factory-defined values of all user-settable properties. a is a structure array whose field names are the object property names and whose field values are the values of the corresponding properties. If you do not specify an output argument, MATLAB displays the information on the screen.

a = get(0,'FactoryObjectTypePropertyName') returns the factory-defined value of the named property for the specified object type. The argument FactoryObjectTypePropertyName is the word Factory concatenated with the object type (e.g., Figure) and the property name (e.g., Color)FactoryFigureColor.

a = get(h,'Default') returns all default values currently defined on object h. a is a structure array whose field names are the object property names and whose field values are the values of the corresponding properties. If you do not specify an output argument, MATLAB displays the information on the screen.

a = get(h,'DefaultObjectTypePropertyName') returns the factory-defined value of the named property for the specified object type. The argument DefaultObjectTypePropertyName is the word Default concatenated with the object type (e.g., Figure) and the property name (e.g., Color).

DefaultFigureColor

Examples

You can obtain the default value of the LineWidth property for line graphics objects defined on the root level with the statement

get(0,'DefaultLineLineWidth')

ans =

     0.5000

To query a set of properties on all axes children, define a cell array of property names:

props = {'HandleVisibility', 'Interruptible';

       'SelectionHighlight', 'Type'};

output = get(get(gca,'Children'),props);

The variable output is a cell array of dimension length(get(gca,'Children')-by-4.

For example, type

patch;surface;text;line

output = get(get(gca,'Children'),props)

output =

    'on'    'on'    'on'    'line'

    'on'    'off'   'on'    'text'

    'on'    'on'    'on'    'surface'

    'on'    'on'    'on'    'patch'

findobj

Locate graphics objects with specific properties

Syntax

findobj
h = findobj
h = findobj('PropertyName',PropertyValue,...)
h = findobj('PropertyName',PropertyValue,'-logicaloperator', PropertyName',PropertyValue,...)
h = findobj('-regexp','PropertyName','regexp',...)
h = findobj('-property','PropertyName')
h = findobj(objhandles,...)
h = findobj(objhandles,'-depth',d,...)
h = findobj(objhandles,'flat','PropertyName',PropertyValue,...)

Description

findobj returns handles of the root object and all its descendants without assigning the result to a variable.

h = findobj returns handles of the root object and all its descendants.

h = findobj('PropertyName',PropertyValue,...) returns handles of all graphics objects having the property PropertyName, set to the value PropertyValue. You can specify more than one property/value pair, in which case, findobj returns only those objects having all specified values.

h = findobj('PropertyName',PropertyValue,'-logicaloperator', PropertyName',PropertyValue,...) applies the logical operator to the property value matching. Possible values for -logicaloperator are:

-and

-or

-xor

-not

See Logical Operators for an explanation of logical operators.

h = findobj('-regexp','PropertyName','regexp',...) matches objects using regular expressions as if the value of you passed the property PropertyName to the regexp function as

regexp(PropertyValue,'regexp')

If a match occurs, findobj returns the object handle. See the regexp function for information on how the MATLAB software uses regular expressions.

h = findobj('-property','PropertyName') finds all objects having the specified property.

h = findobj(objhandles,...) restricts the search to objects listed in objhandles and their descendants.

h = findobj(objhandles,'-depth',d,...) specifies the depth of the search. The depth argument d controls how many levels under the handles in objhandles MATLAB traverses. Specify d as inf to get the default behavior of all levels. Specify d as 0 to get the same behavior as using the flat argument.

h = findobj(objhandles,'flat','PropertyName',PropertyValue,...) restricts the search to those objects listed in objhandles and does not search descendants.

findobj returns an error if a handle refers to a nonexistent graphics object.

findobj correctly matches any legal property value. For example,

findobj('Color','r')

finds all objects having a Color property set to red, r, or [1 0 0].

When a graphics object is a descendant of more than one object identified in objhandles, MATLAB searches the object each time findobj encounters its handle. Therefore, implicit references to a graphics object can result in multiple returns of its handle.

To find handle objects that meet specified conditions, use handle.findobj.

Examples

Find all line objects in the current axes:

h = findobj(gca,'Type','line')

Find all objects having a Label set to 'foo' and a String set to 'bar':

h = findobj('Label','foo','-and','String','bar');

Find all objects whose String is not 'foo' and is not 'bar':

h = findobj('-not','String','foo','-not','String','bar');

Find all objects having a String set to 'foo' and a Tag set to 'button one' and whose Color is not 'red' or 'blue':

h = findobj('String','foo','-and','Tag','button one',...

    '-and','-not',{'Color','red','-or','Color','blue'})

Find all objects for which you have assigned a value to the Tag property (that is, the value is not the empty string ''):

h = findobj('-regexp','Tag','[^'']')

Find all children of the current figure that have their BackgroundColor property set to a certain shade of gray ([.7 .7 .7]). This statement also searches the current figure for the matching property value pair.

h = findobj(gcf,'-depth',1,'BackgroundColor',[.7 .7 .7])

Matlab二维图形绘制函数

%  plot   线性坐标标示绘制曲线图

%  loglog   对数坐标标示绘制曲线图

%  semilogx   对数x坐标,线性y坐标绘制曲线图

%  semilogy   线性x坐标,对数y坐标绘制曲线图

%  plotyy       一个x坐标,左右各有y坐标绘制曲线图

%  contour       绘制等值线图

%  contourf     绘制彩色填充的等值线图

%  pcolor         伪彩色图

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 to plot(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 Yn are plotted against the columns of Xn. plot automatically chooses colors and line styles in the order specified by ColorOrder and LineStyleOrder properties 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.

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)

loglog

Log-log scale plot

Syntax

loglog(Y)
loglog(X1,Y1,...)
loglog(X1,Y1,LineSpec,...)
loglog(...,'PropertyName',PropertyValue,...)
h = loglog(...)

Description

loglog(Y) plots the columns of Y versus their index if Y contains real numbers. If Y contains complex numbers, loglog(Y) and loglog(real(Y),imag(Y)) are equivalent. loglog ignores the imaginary component in all other uses of this function.

loglog(X1,Y1,...) plots all Xn versus Yn pairs. If only Xn or Yn is a matrix, loglog plots the vector argument versus the rows or columns of the matrix, along the dimension of the matrix whose length matches the length of the vector. If the matrix is square, its columns plot against the vector if their lengths match.

loglog(X1,Y1,LineSpec,...) plots all lines defined by the Xn,Yn,LineSpec triples, where LineSpec determines line type, marker symbol, and color of the plotted lines. You can mix Xn,Yn,LineSpec triples with Xn,Yn pairs, for example,

loglog(X1,Y1,X2,Y2,LineSpec,X3,Y3)

loglog(...,'PropertyName',PropertyValue,...) sets property values for all lineseries properties graphics objects created by loglog.

h = loglog(...) returns a column vector of handles to lineseries graphics objects, one handle per line.

Examples

Create a simple loglog plot with square markers.

x = logspace(-1,2);

loglog(x,exp(x),'-s')

grid on

semilogx

Semilogarithmic plot

Syntax

semilogx(Y)
semilogx(X1,Y1,...)
semilogx(X1,Y1,LineSpec,...)
semilogx(...,'PropertyName',PropertyValue,...)
h = semilogx(...)

Description

semilogx plot data as logarithmic scales for the x-axis.

semilogx(Y) creates a plot using a base 10 logarithmic scale for the x-axis and a linear scale for the y-axis. It plots the columns of Y versus their index if Y contains real numbers. semilogx(Y) is equivalent to semilogx(real(Y), imag(Y)) if Y contains complex numbers. semilogx ignores the imaginary component in all other uses of this function.

semilogx(X1,Y1,...) plots all Xn versus Yn pairs. If only Xn or Yn is a matrix, semilogx plots the vector argument versus the rows or columns of the matrix, along the dimension of the matrix whose length matches the length of the vector. If the matrix is square, its columns plot against the vector if their lengths match.

semilogx(X1,Y1,LineSpec,...) plots all lines defined by the Xn,Yn,LineSpec triples. LineSpec determines line style, marker symbol, and color of the plotted lines.

semilogx(...,'PropertyName',PropertyValue,...) sets property values for all lineseries properties graphics objects created by semilogx.

h = semilogx(...) return a vector of handles to lineseries graphics objects, one handle per line.

Tips

If you do not specify a color when plotting more than one line, semilogx automatically cycle through the colors and line styles in the order specified by the current axes ColorOrder and LineStyleOrder properties.

You can mix Xn,Yn pairs with Xn,Yn,LineSpec triples; for example,

semilogx(X1,Y1,X2,Y2,LineSpec,X3,Y3)

If you attempt to add a loglog, semilogx, or semilogy plot to a linear axis mode graph with hold on, the axis mode remains as it is and the new data plots as linear.

Examples

Create a simple semilogx plot.

x = 0:0.1:10;

semilogx(10.^x,x)

semilogy

Semilogarithmic plot

Syntax

semilogy(Y)
semilogy(X1,Y1,...)
semilogy(X1,Y1,LineSpec,...)
semilogy(...,'PropertyName',PropertyValue,...)
h = semilogy(...)

Description

semilogy plots data with logarithmic scale for the y-axis.

semilogy(Y) creates a plot using a base 10 logarithmic scale for the y-axis and a linear scale for the x-axis. It plots the columns of Y versus their index if Y contains real numbers. semilogy(Y) is equivalent to semilogy(real(Y), imag(Y)) if Y contains complex numbers. semilogy ignores the imaginary component in all other uses of this function.

semilogy(X1,Y1,...) plots all Xn versus Yn pairs. If only Xn or Yn is a matrix, semilogy plots the vector argument versus the rows or columns of the matrix, along the dimension of the matrix whose length matches the length of the vector. If the matrix is square, its columns plot against the vector if their lengths match.

semilogy(X1,Y1,LineSpec,...) plots all lines defined by the Xn,Yn,LineSpec triples. LineSpec determines line style, marker symbol, and color of the plotted lines.

semilogy(...,'PropertyName',PropertyValue,...) sets property values for all lineseries properties graphics objects created by semilogy.

h = semilogy(...) returns a vector of handles to lineseries graphics objects, one handle per line.

plotyy

2-D line plots with y-axes on both left and right side

Syntax

plotyy(X1,Y1,X2,Y2)
plotyy(X1,Y1,X2,Y2,function)
plotyy(X1,Y1,X2,Y2,'function1','function2')
[AX,H1,H2] = plotyy(...)

Description

plotyy(X1,Y1,X2,Y2) plots X1 versus Y1 with y-axis labeling on the left and plots X2 versus Y2 with y-axis labeling on the right.

plotyy(X1,Y1,X2,Y2,function) uses the specified plotting function to produce the graph.

function can be either a function handle or a string specifying plot, semilogx, semilogy, loglog, stem, or any MATLAB function that accepts the syntax

h = function(x,y)

For example,

plotyy(x1,y1,x2,y2,@loglog) % function handle

plotyy(x1,y1,x2,y2,'loglog') % string

Function handles enable you to access user-defined subfunctions and can provide other advantages. See @ for more information on using function handles.

plotyy(X1,Y1,X2,Y2,'function1','function2') uses function1(X1,Y1) to plot the data for the left axis and function2(X2,Y2) to plot the data for the right axis.

[AX,H1,H2] = plotyy(...) returns the handles of the two axes created in AX and the handles of the graphics objects from each plot in H1 and H2. AX(1) is the left axes and AX(2) is the right axes.

Examples

This example graphs two mathematical functions using plot as the plotting function. The two y-axes enable you to display both sets of data on one graph even though relative values of the data are quite different.

figure

x = 0:0.01:20;

y1 = 200*exp(-0.05*x).*sin(x);

y2 = 0.8*exp(-0.5*x).*sin(10*x);

[AX,H1,H2] = plotyy(x,y1,x,y2,'plot');

You can use the handles returned by plotyy to label the axes and set the line styles used for plotting. With the axes handles you can specify the YLabel properties of the left- and right-side y-axis:

set(get(AX(1),'Ylabel'),'String','Slow Decay')

set(get(AX(2),'Ylabel'),'String','Fast Decay')

Use the xlabel and title commands to label the x-axis and add a title:

xlabel('Time (\musec)')

title('Multiple Decay Rates')

Use the line handles to set the LineStyle properties of the left- and right-side plots:

set(H1,'LineStyle','--')

set(H2,'LineStyle',':')

contour

Contour plot of matrix

Syntax

contour(Z)
contour(Z,n)
contour(Z,v)
contour(X,Y,Z)
contour(X,Y,Z,n)
contour(X,Y,Z,v)
contour(...,LineSpec)
contour(axes_handle,...)
[C,h] = contour(...)

Description

A contour plot displays isolines of matrix Z. Label the contour lines using clabel.

contour(Z) draws a contour plot of matrix Z, where Z is interpreted as heights with respect to the x-y plane. Z must be at least a 2-by-2 matrix that contains at least two different values. The number of contour lines and the values of the contour lines are chosen automatically based on the minimum and maximum values of Z. The ranges of the x- and y-axis are [1:n] and [1:m], where [m,n] = size(Z).

contour(Z,n) draws a contour plot of matrix Z with n contour levels where n is a scalar.

contour(Z,v) draws a contour plot of matrix Z with contour lines at the data values specified in the monotonically increasing vector v. The number of contour levels is equal to length(v). To draw a single contour of level i, use contour(Z,[i i]). Specifying the vector v sets the LevelListMode to manual to allow user control over contour levels. See contourgroup properties for more information.

contour(X,Y,Z), contour(X,Y,Z,n), and contour(X,Y,Z,v) draw contour plots of Z using X and Y to determine the x- and y-axis limits. When X and Y are matrices, they must be the same size as Z and must be monotonically increasing.

contour(...,LineSpec) draws the contours using the line type and color specified by LineSpec. contour ignores marker symbols.

contour(axes_handle,...) plots into axes axes_handle instead of gca.

[C,h] = contour(...) returns a contour matrix, C, that contains the x, y coordinates and contour levels for contour lines derived by the low-level contourc function, and a handle, h, to a contourgroup object. The clabel function uses contour matrix C to label the contour lines. ContourMatrix is also a read-only contourgroup property that you can obtain from the returned handle.

Use contourgroup object properties to control the contour plot appearance.

If X or Y is irregularly spaced, contour calculates contours using a regularly spaced contour grid, and then transforms the data to X or Y.

Examples

Contour Graph of a Data Set

Load the penny data set, which is a 128x128 grid of the surface relief of a U.S. penny. It generates a variable P. To contour this data, pass the matrix into the contour function. You have to flip the graph using flipud to see the actual contour of the image on the penny:

load penny;

figure;

contour(flipud(P));

axis square;

Contour Graph of a Matrix

Consider plotting the penny dataset with respect to the diameter distance. Assume the starting point to be 1mm and ending at around 15mm, we need 128 data points on both x and y axes because the dataset is a 128x128 double. To generate 128 elements for both axes, we use linspace function here.

x = linspace(1,15,128);

y = linspace(1,15,128);

figure;

contour(x,y,flipud(P));

axis square;

colormap('Copper');

xlabel('X Distance(in mm)');

ylabel('Y Distance(in mm)');

Contour Graph with Specified Number of Contour Lines

To plot a contour with more levels,

figure;

contour(x,y,flipud(P),50);

axis square;

colormap('Copper');

Contour Graph of a Function

Create a contour plot of the function:

z = xe(–x2 – y2)

over the range –2 ≤ x ≤ 2, –2 ≤ y ≤ 3.

Evaluate the function to create matrix, Z. Use the meshgrid function to generate the values used to evaluate the function within the specified range:

[X,Y] = meshgrid(-2:.2:2,-2:.2:3);

Z = X.*exp(-X.^2-Y.^2);

Generate the contour plot of Z:

Display contour labels by setting the ShowText property to on.

Label every other contour line by setting the TextStep property to twice the contour interval (that is, two times the LevelStep property).

Use a smoothly varying colormap.

[C,h] = contour(X,Y,Z);

set(h,'ShowText','on','TextStep',get(h,'LevelStep')*2)

colormap cool

Smoothing Contour Data

Use interp2 to smooth contour lines. Also set the contour label text BackgroundColor to a light yellow and the EdgeColor to light gray.

Z = peaks;

[C,h] = contour(interp2(Z,4));

text_handle = clabel(C,h);

set(text_handle,'BackgroundColor',[1 1 .6],...

    'Edgecolor',[.7 .7 .7])

contourf

Filled 2-D contour plot

Syntax

contourf(Z)
contourf(Z,n)
contourf(Z,v)
contourf(X,Y,Z)
contourf(X,Y,Z,n)
contourf(X,Y,Z,v)
contourf(...,LineSpec)
contourf(axes_handle,...)
contour(axes_handle,...)
[C,h] = contourf(...)

Description

A filled contour plot displays isolines calculated from matrix Z and fills the areas between the isolines using constant colors corresponding to the current figure's colormap.

contourf(Z) draws a filled contour plot of matrix Z, where Z is interpreted as heights with respect to the x-y plane. Z must be at least a 2-by-2 matrix that contains at least two different values. The number of contour lines and the values of the contour lines are chosen automatically based on the minimum and maximum values of Z. The ranges of the x- and y-axis are [1:n] and [1:m], where [m,n] = size(Z).

contourf(Z,n) draws a filled contour plot of matrix Z with n contour levels.

contourf(Z,v) draws a filled contour plot of matrix Z with contour lines at the data values specified in the monotonically increasing vector v. The number of contour levels is equal to length(v). To draw a single contour of level i, use contour(Z,[i i]). Specifying the vector v sets the LevelListMode to manual to allow user control over contour levels. See contourgroup properties for more information.

contourf(X,Y,Z), contourf(X,Y,Z,n), and contourf(X,Y,Z,v) draw filled contour plots of Z using X and Y to determine the x- and y-axis limits. When X and Y are matrices, they must be the same size as Z and must be monotonically increasing.

contourf(...,LineSpec) draws the contour lines using the line type and color specified by LineSpec. contourf ignores marker symbols.

contourf(axes_handle,...) plots into the axes with the handle axes_handle instead of into the current axes (gca).

contour(axes_handle,...) plots into axes gerkaxes_handle instead of gca.

[C,h] = contourf(...) returns a contour matrix, C, that contains the x, y coordinates and contour levels for contour lines derived by the low-level contourc function, and a handle, h, to a contourgroup object containing the filled contours. The clabel function uses contour matrix C to label the contour lines. ContourMatrix is also a read-only Contourgroup property that you can obtain from the returned handle.

Examples

Create a filled contour plot of the peaks function with contour matrix and contourgroup object handle as output and autumn colormap.

[C,h] = contourf(peaks(20),10);

colormap autumn

pcolor

Pseudocolor (checkerboard) plot

Syntax

pcolor(C)
pcolor(X,Y,C)
pcolor(axes_handles,...)
h = pcolor(...)

Description

A pseudocolor plot is a rectangular array of cells with colors determined by C. MATLAB creates a pseudocolor plot using each set of four adjacent points in C to define a surface rectangle (i.e., cell).

The default shading is faceted, which colors each cell with a single color. The last row and column of C are not used in this case. With shading interp, each cell is colored by bilinear interpolation of the colors at its four vertices, using all elements of C.

The minimum and maximum elements of C are assigned the first and last colors in the colormap. Colors for the remaining elements in C are determined by a linear mapping from value to colormap element.

pcolor(C) draws a pseudocolor plot. The elements of C are linearly mapped to an index into the current colormap. The mapping from C to the current colormap is defined by colormap and caxis.

pcolor(X,Y,C) draws a pseudocolor plot of the elements of C at the locations specified by X and Y. The plot is a logically rectangular, two-dimensional grid with vertices at the points [X(i,j), Y(i,j)]. X and Y are vectors or matrices that specify the spacing of the grid lines. If X and Y are vectors, X corresponds to the columns of C and Y corresponds to the rows. If X and Y are matrices, they must be the same size as C.

pcolor(axes_handles,...) plots into the axes with handle axes_handle instead of the current axes (gca).

h = pcolor(...) returns a handle to a surface graphics object.

Examples

A Hadamard matrix has elements that are +1 and -1. A colormap with only two entries is appropriate when displaying a pseudocolor plot of this matrix.

pcolor(hadamard(20))

colormap(gray(2))

axis ij

axis square

A simple color wheel illustrates a polar coordinate system.

n = 6;

r = (0:n)'/n;

theta = pi*(-n:n)/n;

X = r*cos(theta);

Y = r*sin(theta);

C = r*cos(2*theta);

pcolor(X,Y,C)

axis equal tight

legend

Graph legend for lines and patches

Syntax

legend('string1','string2',...)
legend(h,'string1','string2',...)
legend(M)
legend(h,M)
legend(M,'parameter_name','parameter_value',...)
legend(h,M,'parameter_name','parameter_value',...)
legend(axes_handle,...)
legend('off'), legend(axes_handle,'off')
legend('toggle'), legend(axes_handle,'toggle')
legend('hide'), legend(axes_handle,'hide')
legend('show'), legend(axes_handle,'show')
legend('boxoff'), legend(axes_handle,'boxoff')
legend('boxon'), legend(axes_handle,'boxon')
legend_handle = legend(...)
legend(...,'Location','location')
legend(...,'Orientation','orientation')
[legend_h,object_h,plot_h,text_strings] = legend(...)

Description

legend places a legend on various types of graphs (line plots, bar graphs, pie charts, etc.). For each line plotted, the legend shows a sample of the line type, marker symbol, and color beside the text label you specify. When plotting filled areas (patch or surface objects), the legend contains a sample of the face color next to the text label.

The font size and font name for the legend strings match the axes FontSize and FontName properties.

legend('string1','string2',...) displays a legend in the current axes using the specified strings to label each set of data.

legend(h,'string1','string2',...) displays a legend on the plot containing the objects identified by the handles in the vector h and uses the specified strings to label the corresponding graphics object (line, barseries, etc.).

legend(M) adds a legend containing the rows of the matrix or cell array of strings M as labels. For matrices, this is the same as legend(M(1,:),M(2,:),...).

legend(h,M) associates each row of the matrix or cell array of strings M with the corresponding graphics object (patch or line) in the vector of handles h.

legend(M,'parameter_name','parameter_value',...) and legend(h,M,'parameter_name','parameter_value',...) allow parameter/value pairs to be set when creating a legend (you can also assign them with set or with the Property Editor or Property Inspector). M must be a cell array of names. Legends inherit the properties of axes, although not all of them are relevant to legend objects.

legend(axes_handle,...) displays the legend for the axes specified by axes_handle.

legend('off'), legend(axes_handle,'off') removes the legend in the current axes or the axes specified by axes_handle.

legend('toggle'), legend(axes_handle,'toggle') toggles the legend on or off. If no legend exists for the current axes, one is created using default strings.

The default string for an object is the value of the object's DisplayName property, if you have defined a value for DisplayName (which you can do using the Property Editor or calling set). Otherwise, legend constructs a string of the form data1, data2, etc. Setting display names is useful when you are experimenting with legends and might forget how objects in a lineseries, for example, are ordered.

When you specify legend strings in a legend command, their respective DisplayNames are set to these strings. If you delete a legend and then create a new legend without specifying labels for it, the values of DisplayName are (re)used as label names. Naturally, the associated plot objects must have a DisplayName property for this to happen: all _series and _group plot objects have a DisplayName property; Handle Graphics primitives, such as line and patch, do not.

Legends for graphs that contain groups of objects such as lineseries, barseries, contourgroups, etc. created by high-level plotting commands such as plot, bar, contour, etc., by default display a single legend entry for the entire group, regardless of how many member objects it contains. However, you can customize such legends to show individual entries for all or selected member objects and assign a unique DisplayName to any of them. You control how groups appear in the legend by setting values for their Annotation and DisplayName properties with code. For information and examples about customizing legends in this manner, see Controlling Legends in the MATLAB Graphics documentation.

You can specify EdgeColor and TextColor as RGB triplets or as ColorSpecs. You cannot set these colors to 'none'. To hide the box surrounding a legend, set the Box property to 'off'. To allow the background to show through the legend box, set the legend's Color property to 'none', for example,

set(legend_handle, 'Box', 'off')

set(legend_handle, 'Color', 'none')

This is similar to the effect of the command legend boxoff, except that boxoff also hides the legend's border.

You can use a legend's handle to set text properties for all the strings in a legend at once with a cell array of strings, rather than looping through each of them. See the last line of the example below, which demonstrates setting a legend's Interpreter property. In that example, you could reset the String property of the legend as follows:

set(h,'String',{'cos(x)','sin(x)'})

See the documentation for Text Properties for additional details.

legend('hide'), legend(axes_handle,'hide') makes the legend in the current axes or the axes specified by axes_handle invisible.

legend('show'), legend(axes_handle,'show') makes the legend in the current axes or the axes specified by axes_handle visible. A legend is created if one did not exist previously. Legends created automatically are limited to depict only the first 20 lines in the plot; if you need more legend entries, you can manually create a legend for them all with legend('string1','string2',...) syntax.

legend('boxoff'), legend(axes_handle,'boxoff') removes the box from the legend in the current axes or the axes specified by axes_handle, and makes its background transparent.

legend('boxon'), legend(axes_handle,'boxon') adds a box with an opaque background to the legend in the current axes or the axes specified by axes_handle.

You can also type the above six commands using the syntax

legend keyword

If the keyword is not recognized, it is used as legend text, creating a legend or replacing the current legend.

legend_handle = legend(...) returns the handle to the legend on the current axes, or [] if no legend exists.

legend(...,'Location','location') uses location to determine where to place the legend. location can be either be a 1–by-4 position vector

legend(...,'Orientation','orientation') creates a legend with the legend items arranged in the specified orientation. orientation can be vertical (the default) or horizontal.

[legend_h,object_h,plot_h,text_strings] = legend(...) returns

legend_h — Handle of the legend axes

object_h — Handles of the line, patch, and text graphics objects used in the legend

plot_h — Handles of the lines and other objects used in the plot

text_strings — Cell array of the text strings used in the legend

The properties that legends do not share with axes are

Location

Orientation

EdgeColor

TextColor

Interpreter

String

Examples

Add a legend to a graph showing a sine and cosine function. The default location is upper right, within the axes:

figure

x = -pi:pi/20:pi;

plot(x,cos(x),'-ro',x,sin(x),'-.b')

hleg1 = legend('cos_x','sin_x');

The legend reflects that plot specified a solid, red line ('-ro') for the cosine function and a dash-dot, blue line ('-.b') for the sine function.

Update the legend. Use the returned legend handle, hleg1, to move the legend to the upper left. Also turn off the TeX interpreter to render underscores in legend text literally rather than as subscripts:

    set(hleg1,'Location','NorthWest')

    set(hleg1,'Interpreter','none')

Use besselj to plot Bessel functions for orders 1, 2, and 3. Add a legend for the lines at the upper right, outside the axes.

figure

x = 0:.2:12;

plot(x,besselj(1,x),x,besselj(2,x),x,besselj(3,x));

hleg = legend('First','Second','Third',...

              'Location','NorthEastOutside')

% Make the text of the legend italic and color it brown

set(hleg,'FontAngle','italic','TextColor',[.3,.2,.1])

Create a bar graph and overlay a line plot on it by setting hold on. Create a legend that reflects both graphs and locate it to the lower right, outside the axes:

figure

stream = RandStream('mrg32k3a','Seed',4);

y1 = rand(stream,10,5);

hb = bar(y1,'stacked'); colormap(summer); hold on

y2 = rand(stream,10,1);

hp = plot(1:10,y2,'marker','square','markersize',12,...

       'markeredgecolor','y','markerfacecolor',[.6,0,.6],...

       'linestyle','-','color','r','linewidth',2); hold off

legend([hb,hp],'Carrots','Peas','Peppers','Green Beans',...

        'Cucumbers','Eggplant','Location','SouthEastOutside')

Matlab三维图形绘制函数

% plot3     绘制三维曲线图

% contour3  绘制三维等值线图

% mesh      绘制三维表面图

% meshc     绘制三维表面图和二维等值线图

% surf        绘制三维彩色表面图

% surfc       绘制三维彩色表面图和对应的二维彩色等值线图

% slice       切片图

% ellipsoid     椭球面图

% sphere        球面图

plot3

3-D line plot

Syntax

plot3(X1,Y1,Z1,...)
plot3(X1,Y1,Z1,LineSpec,...)
plot3(...,'PropertyName',PropertyValue,...)
h = plot3(...)

Description

The plot3 function displays a three-dimensional plot of a set of data points.

plot3(X1,Y1,Z1,...), where X1, Y1, Z1 are vectors or matrices, plots one or more lines in three-dimensional space through the points whose coordinates are the elements of X1, Y1, and Z1.

plot3(X1,Y1,Z1,LineSpec,...) creates and displays all lines defined by the Xn,Yn,Zn,LineSpec quads, where LineSpec is a line specification that determines line style, marker symbol, and color of the plotted lines.

plot3(...,'PropertyName',PropertyValue,...) sets properties to the specified property values for all line graphics objects created by plot3.

h = plot3(...) returns a column vector of handles to lineseries graphics objects, with one handle per object.

Tips

If one or more of X1, Y1, Z1 is a vector, the vectors are plotted versus the rows or columns of the matrix, depending whether the vectors' lengths equal the number of rows or the number of columns.

You can mix Xn,Yn,Zn triples with Xn,Yn,Zn,LineSpec quads, for example,

plot3(X1,Y1,Z1,X2,Y2,Z2,LineSpec,X3,Y3,Z3)

See LineSpec and plot for information on line types and markers.

Examples

Plot a three-dimensional helix.

t = 0:pi/50:10*pi;

plot3(sin(t),cos(t),t)

xlabel('sin(t)')

ylabel('cos(t)')

zlabel('t')

grid on

axis square

contour3

3-D contour plot

Syntax

contour3(Z)
contour3(Z,n)
contour3(Z,v)
contour3(X,Y,Z)
contour3(X,Y,Z,n)
contour3(X,Y,Z,v)
contour3(...,LineSpec)
contour3(axes_handle,...)
[C,h] = contour3(...)

Description

contour3 creates a 3-D contour plot of a surface defined on a rectangular grid.

contour3(Z) draws a contour plot of matrix Z in a 3-D view. Z is interpreted as heights with respect to the x-y plane. Z must be at least a 2-by-2 matrix that contains at least two different values. The number of contour levels and the values of contour levels are chosen automatically based on the minimum and maximum values of Z. The ranges of the x- and y-axis are [1:n] and [1:m], where [m,n] = size(Z).

contour3(Z,n) draws a contour plot of matrix Z with n contour levels in a 3-D view.

contour3(Z,v) draws a contour plot of matrix Z with contour lines at the values specified in vector v. The number of contour levels is equal to length(v). To draw a single contour of level i, use contour(Z,[i i]). Specifying the vector v sets the LevelListMode to manual to allow user control over contour levels. See contourgroup properties for more information.

contour3(X,Y,Z), contour3(X,Y,Z,n), and contour3(X,Y,Z,v) draw contour plots of Z using X and Y to determine the x- and y-axis limits. If X is a matrix, X(1,:) defines the x-axis. If Y is a matrix, Y(:,1) defines the y-axis. When X and Y are matrices, they must be the same size as Z and must be monotonically increasing.

contour3(...,LineSpec) draws the contour lines using the line type and color specified by LineSpec. contour3 ignores marker symbols.

contour3(axes_handle,...) plots into the axes with the handle axes_handle instead of into the current axes (gca).

[C,h] = contour3(...) returns a contour matrix, C, that contains the x, y coordinates and contour levels for contour lines derived by the low-level contourc function, and a handle, h, to an array of handles to graphics objects. The clabel function uses contour matrix C to label the contour lines. The graphic objects that contour3 creates are patch objects, or if you specify a LineSpec argument, line objects.

Examples

Plot the three-dimensional contour of a function and superimpose a surface plot to enhance visualization of the function.

[X,Y] = meshgrid([-2:.25:2]);

Z = X.*exp(-X.^2-Y.^2);

contour3(X,Y,Z,30)

surface(X,Y,Z,'EdgeColor',[.8 .8 .8],'FaceColor','none')

grid off

view(-15,25)

colormap cool

mesh

Mesh plot

Syntax

mesh(X,Y,Z)
mesh(Z)
mesh(...,C)
mesh(...,'PropertyName',PropertyValue,...)
mesh(axes_handles,...)
h = mesh(...)

Description

mesh(X,Y,Z) draws a wireframe mesh with color determined by Z, so color is proportional to surface height. If X and Y are vectors, length(X) = n and length(Y) = m, where [m,n] = size(Z). In this case, (X(j), Y(i), Z(i,j)) are the intersections of the wireframe grid lines; X and Y correspond to the columns and rows of Z, respectively. If X and Y are matrices, (X(i,j), Y(i,j), Z(i,j)) are the intersections of the wireframe grid lines.

mesh(Z) draws a wireframe mesh using X = 1:n and Y = 1:m, where [m,n] = size(Z). The height, Z, is a single-valued function defined over a rectangular grid. Color is proportional to surface height.

mesh(...,C) draws a wireframe mesh with color determined by matrix C. MATLAB performs a linear transformation on the data in C to obtain colors from the current colormap. If X, Y, and Z are matrices, they must be the same size as C.

mesh(...,'PropertyName',PropertyValue,...) sets the value of the specified surface property. Multiple property values can be set with a single statement.

mesh(axes_handles,...) plots into the axes with handle axes_handle instead of the current axes (gca).

h = mesh(...) returns a handle to a Surfaceplot graphics object.

Examples

Evaluate sin(r)/r, or the sinc function

figure;

[X,Y] = meshgrid(-8:.5:8);

R = sqrt(X.^2 + Y.^2) + eps;

Z = sin(R)./R;

mesh(Z);

Displaying the sinc function between -8 and 8 on a 2-D grid

figure;

mesh(X,Y,Z);

axis([-8 8 -8 8 -0.5 1]);

Specifying color matrix for the data in the mesh function

C = gradient(Z);

figure;

mesh(X,Y,Z,C);

Specifying the property name-value pairs in the argument list.

C = del2(Z);

h = axes;

mesh(h,Z,C,'FaceLighting','gouraud','LineWidth',0.3);

meshc

Plot a contour graph under mesh graph

Syntax

meshc(X,Y,Z)
meshc(Z)
meshc(...,C)
meshc(axes_handles,...)
h = meshc(...)

Description

meshc(X,Y,Z) draws a wireframe mesh and a contour plot under it with color determined by Z, so color is proportional to surface height. If X and Y are vectors, length(X) = n and length(Y) = m, where [m,n] = size(Z). In this case, (X(j), Y(i), Z(i,j)) are the intersections of the wireframe grid lines; X and Y correspond to the columns and rows of Z, respectively. If X and Y are matrices, (X(i,j), Y(i,j), Z(i,j)) are the intersections of the wireframe grid lines.

meshc(Z) draws a contour plot under wireframe mesh using X = 1:n and Y = 1:m, where [m,n] = size(Z). The height, Z, is a single-valued function defined over a rectangular grid. Color is proportional to surface height.

meshc(...,C) draws a meshc graph with color determined by matrix C. MATLAB performs a linear transformation on the data in C to obtain colors from the current colormap. If X, Y, and Z are matrices, they must be the same size as C.

meshc(axes_handles,...) plots into the axes with handle axes_handle instead of the current axes (gca).

h = meshc(...) returns a handle to a Surfaceplot graphics object.

Tips

meshc does not accept complex inputs.

A mesh is drawn as a Surfaceplot graphics object with the viewpoint specified by view(3). The face color is the same as the background color (to simulate a wireframe with hidden-surface elimination), or none when drawing a standard see-through wireframe. The current colormap determines the edge color. The hidden command controls the simulation of hidden-surface elimination in the mesh, and the shading command controls the shading model.

Examples

Produce a combination mesh and contour plot of the peaks surface with meschc:

figure

[X,Y] = meshgrid(-3:.125:3);

Z = peaks(X,Y);

meshc(Z);

Specifying axes limits for the meshc function.

figure;

meshc(X,Y,Z);

axis([-3 3 -3 3 -10 5]);

surf

3-D shaded surface plot

Syntax

surf(Z)
surf(Z,C)
surf(X,Y,Z)
surf(X,Y,Z,C)
surf(...,'PropertyName',PropertyValue)
surf(axes_handles,...)
h = surf(...)

Description

surf(Z) creates a three-dimensional shaded surface from the z components in matrix Z, using x = 1:n and y = 1:m, where [m,n] = size(Z). The height, Z, is a single-valued function defined over a geometrically rectangular grid. Z specifies the color data, as well as surface height, so color is proportional to surface height.

surf(Z,C) plots the height of Z, a single-valued function defined over a geometrically rectangular grid, and uses matrix C, assumed to be the same size as Z, to color the surface.

surf(X,Y,Z) uses Z for the color data and surface height. X and Y are vectors or matrices defining the x and y components of a surface. If X and Y are vectors, length(X) = n and length(Y) = m, where [m,n] = size(Z). In this case, the vertices of the surface faces are (X(j), Y(i), Z(i,j)) triples. To create X and Y matrices for arbitrary domains, use the meshgrid function.

surf(X,Y,Z,C) uses C to define color. MATLAB performs a linear transformation on this data to obtain colors from the current colormap.

surf(...,'PropertyName',PropertyValue) specifies surface properties along with the data.

surf(axes_handles,...) plots into the axes with handle axes_handle instead of the current axes (gca).

h = surf(...) returns a handle to a Surfaceplot graphics object.

Examples

Color a sphere with the pattern of +1s and -1s in a Hadamard matrix.

k = 5;

n = 2^k-1;

[x,y,z] = sphere(n);

c = hadamard(2^k);

surf(x,y,z,c);

colormap([1  1  0; 0  1  1])

axis equal

surfc

Contour plot under a 3-D shaded surface plot

Syntax

surfc(Z)
surfc(Z,C)
surfc(X,Y,Z)
surfc(X,Y,Z,C)
surfc(...,'PropertyName',PropertyValue)
surfc(axes_handles,...)
h = surfc(...)

Description

surfc(Z) creates a contour plot under the three-dimensional shaded surface from the z components in matrix Z, using x = 1:n and y = 1:m, where [m,n] = size(Z). The height, Z, is a single-valued function defined over a geometrically rectangular grid. Z specifies the color data, as well as surface height, so color is proportional to surface height.

surfc(Z,C) plots the height of Z, a single-valued function defined over a geometrically rectangular grid, and uses matrix C, assumed to be the same size as Z, to color the surface.

surfc(X,Y,Z) uses Z for the color data and surface height. X and Y are vectors or matrices defining the x and y components of a surface. If X and Y are vectors, length(X) = n and length(Y) = m, where [m,n] = size(Z). In this case, the vertices of the surface faces are (X(j), Y(i), Z(i,j)) triples. To create X and Y matrices for arbitrary domains, use the meshgrid function.

surfc(X,Y,Z,C) uses C to define color. MATLAB performs a linear transformation on this data to obtain colors from the current colormap.

surfc(...,'PropertyName',PropertyValue) specifies surface properties along with the data.

surfc(axes_handles,...) plots into the axes with handle axes_handle instead of the current axes (gca).

h = surfc(...) returns a handle to a Surfaceplot graphics object.

Examples

Display a surface plot and a contour plot of the peaks surface.

[X,Y,Z] = peaks(30);

surfc(X,Y,Z)

colormap hsv

axis([-3 3 -3 3 -10 5])

slice

Volumetric slice plot

Syntax

slice(V,sx,sy,sz)
slice(X,Y,Z,V,sx,sy,sz)
slice(V,XI,YI,ZI)
slice(X,Y,Z,V,XI,YI,ZI)
slice(...,'method')
slice(axes_handle,...)
h = slice(...)

Description

slice displays orthogonal slice planes through volumetric data.

slice(V,sx,sy,sz) draws slices along the x, y, z directions in the volume V at the points in the vectors sx, sy, and sz. V is an m-by-n-by-p volume array containing data values at the default location X = 1:n, Y = 1:m, Z = 1:p. Each element in the vectors sx, sy, and sz defines a slice plane in the x-, y-, or z-axis direction.

slice(X,Y,Z,V,sx,sy,sz) draws slices of the volume V. X, Y, and Z are three-dimensional arrays specifying the coordinates for V. X, Y, and Z must be monotonic and orthogonally spaced (as if produced by the function meshgrid). The color at each point is determined by 3-D interpolation into the volume V.

slice(V,XI,YI,ZI) draws data in the volume V for the slices defined by XI, YI, and ZI. XI, YI, and ZI are matrices that define a surface, and the volume is evaluated at the surface points. XI, YI, and ZI must all be the same size.

slice(X,Y,Z,V,XI,YI,ZI) draws slices through the volume V along the surface defined by the arrays XI, YI, ZI.

slice(...,'method') specifies the interpolation method. 'method' is 'linear', 'cubic', or 'nearest'.

linear specifies trilinear interpolation (the default).

cubic specifies tricubic interpolation.

nearest specifies nearest-neighbor interpolation.

slice(axes_handle,...) plots into the axes with the handle axes_handle instead of into the current axes object (gca). The axes clim property is set to span the finite values of V.

h = slice(...) returns a vector of handles to surface graphics objects.

Tips

The color drawn at each point is determined by interpolation into the volume V.

Examples

Visualize the function

over the range –2 ≤ x ≤ 2, –2 ≤y ≤2, – 2 ≤ z ≤2:

[x,y,z] = meshgrid(-2:.2:2,-2:.25:2,-2:.16:2);

v = x.*exp(-x.^2-y.^2-z.^2);

xslice = [-1.2,.8,2]; yslice = 2; zslice = [-2,0];

slice(x,y,z,v,xslice,yslice,zslice)

colormap hsv

Slicing At Arbitrary Angles

You can also create slices that are oriented in arbitrary planes. To do this,

Create a slice surface in the domain of the volume (surf, linspace).

Orient this surface with respect to the axes (rotate).

Get the XData, YData, and ZData of the surface (get).

Use this data to draw the slice plane within the volume.

For example, these statements slice the volume in the first example with a rotated plane. Placing these commands within a for loop "passes" the plane through the volume along the z-axis.

for i = -2:.5:2

    hsp = surf(linspace(-2,2,20),linspace(-2,2,20),zeros(20)+i);

    rotate(hsp,[1,-1,1],30)

    xd = get(hsp,'XData');

    yd = get(hsp,'YData');

    zd = get(hsp,'ZData');

    delete(hsp)

    slice(x,y,z,v,[-2,2],2,-2) % Draw some volume boundaries

    hold on

    slice(x,y,z,v,xd,yd,zd)

    hold off

    axis tight

    view(-5,10)  

    drawnow

end

Slicing with a Nonplanar Surface

You can slice the volume with any surface. This example probes the volume created in the previous example by passing a spherical slice surface through the volume.

[xsp,ysp,zsp] = sphere;

slice(x,y,z,v,[-2,2],2,-2)  % Draw some volume boundaries

for i = -3:.2:3

    hsp = surface(xsp+i,ysp,zsp);

    rotate(hsp,[1 0 0],90)

    xd = get(hsp,'XData');

    yd = get(hsp,'YData');

    zd = get(hsp,'ZData');

    delete(hsp)

    hold on

    hslicer = slice(x,y,z,v,xd,yd,zd);

    axis tight

    xlim([-3,3])

    view(-10,35)

    drawnow

    delete(hslicer)

    hold off

end

ellipsoid

Generate ellipsoid

Syntax

[x,y,z] = ellipsoid(xc,yc,zc,xr,yr,zr,n)
[x,y,z] = ellipsoid(xc,yc,zc,xr,yr,zr)
ellipsoid(axes_handle,...)
ellipsoid(...)

Description

[x,y,z] = ellipsoid(xc,yc,zc,xr,yr,zr,n) generates a surface mesh described by three n+1-by-n+1 matrices, enabling surf(x,y,z) to plot an ellipsoid with center (xc,yc,zc) and semi-axis lengths (xr,yr,zr).

[x,y,z] = ellipsoid(xc,yc,zc,xr,yr,zr) uses n = 20.

ellipsoid(axes_handle,...) plots into the axes with handle axes_handle instead of the current axes (gca).

ellipsoid(...) with no output arguments plots the ellipsoid as a surface.

Examples

Generate ellipsoid with size and proportions of a standard U.S. football:

[x, y, z] = ellipsoid(0,0,0,5.9,3.25,3.25,30);

surfl(x, y, z)

colormap copper

axis equal

sphere

Generate sphere

Syntax

sphere
sphere(n)
[X,Y,Z] = sphere(n)

Description

The sphere function generates the x-, y-, and z-coordinates of a unit sphere for use with surf and mesh.

sphere generates a sphere consisting of 20-by-20 faces.

sphere(n) draws a surf plot of an n-by-n sphere in the current figure.

[X,Y,Z] = sphere(n) returns the coordinates of a sphere in three matrices that are (n+1)-by-(n+1) in size. You draw the sphere with surf(X,Y,Z) or mesh(X,Y,Z).

Examples

Generate and plot a sphere.

figure

sphere

axis equal

Plot multiple spheres, translating centers away from the origin:

figure

[x,y,z] = sphere;

surf(x,y,z)  % sphere centered at origin

hold on

surf(x+3,y-2,z)  % sphere centered at (3,-2,0)

surf(x,y+1,z-3)  % sphere centered at (0,1,-3)

daspect([1 1 1])

cylinder

Generate cylinder

Syntax

[X,Y,Z] = cylinder
[X,Y,Z] = cylinder(r)
[X,Y,Z] = cylinder(r,n)
cylinder(axes_handle,...)
cylinder(...)

Description

cylinder generates x-, y-, and z-coordinates of a unit cylinder. You can draw the cylindrical object using surf or mesh, or draw it immediately by not providing output arguments.

[X,Y,Z] = cylinder returns the x-, y-, and z-coordinates of a cylinder with a radius equal to 1. The cylinder has 20 equally spaced points around its circumference.

[X,Y,Z] = cylinder(r) returns the x-, y-, and z-coordinates of a cylinder using r to define a profile curve. cylinder treats each element in r as a radius at equally spaced heights along the unit height of the cylinder. The cylinder has 20 equally spaced points around its circumference.

[X,Y,Z] = cylinder(r,n) returns the x-, y-, and z-coordinates of a cylinder based on the profile curve defined by vector r. The cylinder has n equally spaced points around its circumference.

cylinder(axes_handle,...) plots into the axes with handle axes_handle instead of the current axes (gca).

cylinder(...), with no output arguments, plots the cylinder using surf.

Tips

cylinder treats its first argument as a profile curve. The resulting surface graphics object is generated by rotating the curve about the x-axis, and then aligning it with the z-axis.

Examples

Create a cylinder with randomly colored faces.

cylinder

axis square

h = findobj('Type','surface');

set(h,'CData',rand(size(get(h,'CData'))))

Generate a cylinder defined by the profile function 2+sin(t).

t = 0:pi/10:2*pi;

[X,Y,Z] = cylinder(2+cos(t));

surf(X,Y,Z)

axis square 

坐标轴的设置

daspect

Set or query axes data aspect ratio

Syntax

daspect
daspect([aspect_ratio])
daspect('mode')
daspect('auto')
daspect('manual')
daspect(axes_handle,...)

Description

The data aspect ratio determines the relative scaling of the data units along the x-, y-, and z-axes.

daspect with no arguments returns the data aspect ratio of the current axes.

daspect([aspect_ratio]) sets the data aspect ratio in the current axes to the specified value. Specify the aspect ratio as three relative values representing the ratio of the x-, y-, and z-axis scaling (e.g., [1 1 3] means one unit in x is equal in length to one unit in y and three units in z).

daspect('mode') returns the current value of the data aspect ratio mode, which can be either auto (the default) or manual. See TipsRemarks.

daspect('auto') sets the data aspect ratio mode to auto.

daspect('manual') sets the data aspect ratio mode to manual.

daspect(axes_handle,...) performs the set or query on the axes identified by the first argument, axes_handle. When you do not specify an axes handle, daspect operates on the current axes.

Examples

The following surface plot of the function is useful to illustrate the data aspect ratio. First plot the function over the range –2 ≤ x ≤ 2, –2 ≤ y ≤ 2,

[x,y] = meshgrid([-2:.2:2]);

z = x.*exp(-x.^2 - y.^2);

surf(x,y,z)

Querying the data aspect ratio shows how the surface is drawn.

daspect

ans =

     4  4  1

Setting the data aspect ratio to [1 1 1] produces a surface plot with equal scaling along each axis.

daspect([1 1 1])

pbaspect

Set or query plot box aspect ratio

Syntax

pbaspect
pbaspect([aspect_ratio])
pbaspect('mode')
pbaspect('auto')
pbaspect('manual')
pbaspect(axes_handle,...)

Description

The plot box aspect ratio determines the relative size of the x-, y-, and z-axes.

pbaspect with no arguments returns the plot box aspect ratio of the current axes.

pbaspect([aspect_ratio]) sets the plot box aspect ratio in the current axes to the specified value. Specify the aspect ratio as three relative values representing the ratio of the x-, y-, and z-axes size. For example, a value of [1 1 1] (the default) means the plot box is a cube (although with stretch-to-fill enabled, it may not appear as a cube). See Tips.

pbaspect('mode') returns the current value of the plot box aspect ratio mode, which can be either auto (the default) or manual. See Remarks.

pbaspect('auto') sets the plot box aspect ratio mode to auto.

pbaspect('manual') sets the plot box aspect ratio mode to manual.

pbaspect(axes_handle,...) performs the set or query on the axes identified by the first argument, axes_handle. If you do not specify an axes handle, pbaspect operates on the current axes.

Tips

pbaspect sets or queries values of the axes object PlotBoxAspectRatio and PlotBoxAspectRatioMode properties.

When the plot box aspect ratio mode is auto, the MATLAB software sets the ratio to [1 1 1], but may change it to accommodate manual settings of the data aspect ratio, camera view angle, or axis limits. See the axes DataAspectRatio property for a table listing the interactions between various properties.

Setting a value for the plot box aspect ratio or setting the plot box aspect ratio mode to manual disables the MATLAB stretch-to-fill feature (stretching of the axes to fit the window). This means setting the plot box aspect ratio to its current value,

pbaspect(pbaspect)

can cause a change in the way the graphs look. See the Remarks section of the axes reference description, "Axes Aspect Ratio Properties" in the 3-D Visualization manual, and "Setting Aspect Ratio" in the MATLAB Graphics manual for a discussion of stretch-to-fill.

Examples

The following surface plot of the function is useful to illustrate the plot box aspect ratio. First plot the function over the range –2 ≤ x ≤ 2, –2 ≤ y ≤ 2,

[x,y] = meshgrid([-2:.2:2]);

z = x.*exp(-x.^2 - y.^2);

surf(x,y,z)

Querying the plot box aspect ratio shows that the plot box is square.

pbaspect

ans =

     1  1  1

It is also interesting to look at the data aspect ratio selected by MATLAB.

daspect

ans =

     4  4  1

To illustrate the interaction between the plot box and data aspect ratios, set the data aspect ratio to [1 1 1] and again query the plot box aspect ratio.

daspect([1 1 1])

pbaspect

ans =

     4  4  1

The plot box aspect ratio has changed to accommodate the specified data aspect ratio. Now suppose you want the plot box aspect ratio to be [1 1 1] as well.

pbaspect([1 1 1])

Notice how MATLAB changed the axes limits because of the constraints introduced by specifying both the plot box and data aspect ratios.

You can also use pbaspect to disable stretch-to-fill. For example, displaying two subplots in one figure can give surface plots a squashed appearance. Disabling stretch-to-fill,

upper_plot = subplot(211);

surf(x,y,z)

lower_plot = subplot(212);

surf(x,y,z)

pbaspect(upper_plot,'manual')

xlim

Set or query x-axis limits

Syntax

xlim
xlim([xmin xmax])
xlim('mode')
xlim('auto')
xlim('manual')
xlim(axes_handle,...)

Description

xlim with no arguments returns the limits of the current axes.

xlim([xmin xmax]) sets the axis limits in the current axes to the specified values.

xlim('mode') returns the current value of the axis limits mode, which can be either auto (the default) or manual.

xlim('auto') sets the axis limit mode to auto.

xlim('manual') sets the axis limit mode to manual.

xlim(axes_handle,...) performs the set or query on the axes identified by the first argument, axes_handle. When you do not specify an axes handle, it operates on the current axes.

Tips

xlim sets or queries values of the axes object XLim, and XLimMode property.

When the axis limit mode is set to auto (the default), MATLAB uses limits, which are round numbers, to span the range of the data being displayed. Setting a value for any of the limits also sets the corresponding mode to manual. If you set the limits on an existing graph and want to maintain these limits while adding more graphs, use the hold command.

Examples

This example illustrates how to set the x- and y-axis limits to match the actual range of the data, rather than the rounded values of [-2 3] for the x-axis, [-2 4] for the y-axis and [-0.5 0.5] for z-axis originally selected by MATLAB.

[x,y] = meshgrid([-1.75:.2:3.25]);

z = x.*exp(-x.^2-y.^2);

surf(x,y,z)

xlim([-1.75 3.25])

ylim([-1.75 3.25])

zlim([-0.45 0.45])

ylim

Set or query y-axis limits

Syntax

ylim
ylim([ymin ymax])
ylim('mode')
ylim('auto')
ylim('manual')
ylim(axes_handle,...)

Description

ylim with no arguments returns the limits of the current axes.

ylim([ymin ymax]) sets the axis limits in the current axes to the specified values.

ylim('mode') returns the current value of the axis limits mode, which can be either auto (the default) or manual.

ylim('auto') sets the axis limit mode to auto.

ylim('manual') sets the axis limit mode to manual.

ylim(axes_handle,...) performs the set or query on the axes identified by the first argument, axes_handle. When you do not specify an axes handle, it operates on the current axes.

Tips

ylim set or queries values of the axes object YLimand YLimMode property.

When the axis limit mode is set to auto (the default), MATLAB uses limits, which are round numbers, to span the range of the data being displayed. Setting a value for any of the limits also sets the corresponding mode to manual. If you set the limits on an existing graph and want to maintain these limits while adding more graphs, use the hold command.

Examples

This example illustrates how to set the x- and y-axis limits to match the actual range of the data, rather than the rounded values of [-2 3] for the x-axis and [-2 4] for the y-axis and [-0.5 0.5] for z-axis originally selected by MATLAB.

[x,y] = meshgrid([-1.75:.2:3.25]);

z = x.*exp(-x.^2-y.^2);

surf(x,y,z)

xlim([-1.75 3.25])

ylim([-1.75 3.25])

zlim([-0.45 0.45])

plottools

Show or hide plot tools

Syntax

plottools('on')
plottools('off')
plottools
plottools(figure_handle,...)
plottools(...,'tool')

Description

plottools('on') displays the Figure Palette, Plot Browser, and Property Editor on the current figure, configured as you last used them.

plottools('off') hides the Figure Palette, Plot Browser, and Property Editor on the current figure.

plottools with no arguments, is the same as plottools('on')

plottools(figure_handle,...) displays or hides the plot tools on the specified figure instead of on the current figure.

plottools(...,'tool') operates on the specified tool only. tool can be one of the following strings:

figurepalette

plotbrowser

propertyeditor

view

Viewpoint specification

Syntax

view(az,el)
view([az,el])
view([x,y,z])
view(2)
view(3)
view(ax,...)
[az,el] = view

Description

The position of the viewer (the viewpoint) determines the orientation of the axes. You specify the viewpoint in terms of azimuth and elevation, or by a point in three-dimensional space.

view(az,el) and view([az,el]) set the viewing angle for a three-dimensional plot. The azimuth, az, is the horizontal rotation about the z-axis as measured in degrees from the negative y-axis. Positive values indicate counterclockwise rotation of the viewpoint. el is the vertical elevation of the viewpoint in degrees. Positive values of elevation correspond to moving above the object; negative values correspond to moving below the object.

view([x,y,z]) sets the viewpoint to the Cartesian coordinates x, y, and z. The magnitude of (x,y,z) is ignored.

view(2) sets the default two-dimensional view, az = 0, el = 90.

view(3) sets the default three-dimensional view, az = –37.5, el = 30.

view(ax,...) uses axes ax instead of the current axes.

[az,el] = view returns the current azimuth and elevation.

Examples

View the object from directly overhead.

az = 0;

el = 90;

view(az, el);

Set the view along the y-axis, with the x-axis extending horizontally and the z-axis extending vertically in the figure.

view([0 0]);

Rotate the view about the z-axis by 180º.

az = 180;

el = 90;

view(az, el);

light

Create light object

Syntax

light('PropertyName',propertyvalue,...)
handle = light(...)

Description

light creates a light object in the current axes. Lights affect only patch and surface objects.

light('PropertyName',propertyvalue,...) creates a light object using the specified values for the named properties. For a description of the properties, see Light Properties. The MATLAB software parents the light to the current axes unless you specify another axes with the Parent property.

handle = light(...) returns the handle of the light object created.

Tips

You cannot see a light object per se, but you can see the effects of the light source on patch and surface objects. You can also specify an axes-wide ambient light color that illuminates these objects. However, ambient light is visible only when at least one light object is present and visible in the axes.

You can specify properties as property name/property value pairs, structure arrays, and cell arrays (see set and get for examples of how to specify these data types).

See also the patch and surface AmbientStrength, DiffuseStrength, SpecularStrength, SpecularExponent, SpecularColorReflectance, and VertexNormals properties. Also see the lighting and material commands.

Examples

Light the peaks surface plot with a light source located at infinity and oriented along the direction defined by the vector [1 0 0], that is, along the x-axis.

h = surf(peaks);

set(h,'FaceLighting','phong','FaceColor','interp',...

      'AmbientStrength',0.5)

light('Position',[1 0 0],'Style','infinite');

Setting Default Properties

You can set default light properties on the axes, figure, and root object levels:

set(0,'DefaultLightProperty',PropertyValue...)

set(gcf,'DefaultLightProperty',PropertyValue...)

set(gca,'DefaultLightProperty',PropertyValue...)

where Property is the name of the light property and PropertyValue is the value you are specifying. Use set and get to access light properties.

Matlab特殊绘图函数

bar

Plot bar graph

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 in X.

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.

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.

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.

hist

Histogram plot

Syntax

n = hist(Y)
n = hist(Y,x)
n = hist(Y,nbins)
[n,xout] = hist(...)
hist(...)
hist(axes_handle,...)

Description

A histogram shows the distribution of data values.

n = hist(Y) bins the elements in vector Y into 10 equally spaced containers and returns the number of elements in each container as a row vector. If Y is an m-by-p matrix, hist treats the columns of Y as vectors and returns a 10-by-p matrix n. Each column of n contains the results for the corresponding column of Y. No elements of Y can be complex or of type integer.

n = hist(Y,x) where x is a vector, returns the distribution of Y among length(x) bins with centers specified by x. For example, if x is a 5-element vector, hist distributes the elements of Y into five bins centered on the x-axis at the elements in x, none of which can be complex. Note: use histc if it is more natural to specify bin edges instead of centers.

n = hist(Y,nbins) where nbins is a scalar, uses nbins number of bins.

[n,xout] = hist(...) returns vectors n and xout containing the frequency counts and the bin locations. You can use bar(xout,n) to plot the histogram.

hist(...) without output arguments produces a histogram plot of the output described above. hist distributes the bins along the x-axis between the minimum and maximum values of Y.

hist(axes_handle,...) plots into the axes with handle axes_handle instead of the current axes (gca).

Examples

Generate a bell-curve histogram from Gaussian data.

x = -4:0.1:4;

y = randn(10000,1);

hist(y,x)

Change the color of the graph so that the bins are red and the edges of the bins are white.

h = findobj(gca,'Type','patch');

set(h,'FaceColor','r','EdgeColor','w')

polar

Polar coordinate plot

Syntax

polar(theta,rho)
polar(theta,rho,LineSpec)
polar(axes_handle,...)
h = polar(...)

Description

The polar function accepts polar coordinates, plots them in a Cartesian plane, and draws the polar grid on the plane.

polar(theta,rho) creates a polar coordinate plot of the angle theta versus the radius rho. theta is the angle from the x-axis to the radius vector specified in radians; rho is the length of the radius vector specified in dataspace units.

polar(theta,rho,LineSpec) LineSpec specifies the line type, plot symbol, and color for the lines drawn in the polar plot.

polar(axes_handle,...) plots into the axes with the handle axes_handle instead of into the current axes (gca).

h = polar(...) returns the handle of a line object in h.

Examples

Create a simple polar plot using a dashed red line:

figure

t = 0:.01:2*pi;

polar(t,sin(2*t).*cos(2*t),'--r')

area

Filled area 2-D plot

Syntax

area(Y)
area(X,Y)
area(...,basevalue)
area(...,'PropertyName',PropertyValue,...)
area(axes_handle,...)
h = area(...)

Description

An area graph displays elements in Y as one or more curves and fills the area beneath each curve. When Y is a matrix, the curves are stacked showing the relative contribution of each row element to the total height of the curve at each x interval.

area(Y) plots the vector Y or the sum of each column in matrix Y. The x-axis automatically scales to 1:size(Y,1).

area(X,Y) For vectors X and Y, area(X,Y) is the same as plot(X,Y) except that the area between 0 and Y is filled. When Y is a matrix, area(X,Y) plots the columns of Y as filled areas. For each X, the net result is the sum of corresponding values from the columns of Y.

If X is a vector, length(X) must equal length(Y). If X is a matrix, size(X) must equal size(Y).

area(...,basevalue) specifies the base value for the area fill. The default basevalue is 0. See the BaseValue property for more information.

area(...,'PropertyName',PropertyValue,...) specifies property name and property value pairs for the patch graphics object created by area.

area(axes_handle,...) plots into the axes with the handle axes_handle instead of into the current axes (gca).

h = area(...) returns handles of areaseries graphics objects.

Creating an area graph of an m-by-n matrix creates n areaseries objects (i.e., one per column), whereas a 1-by-n vector creates one areaseries object.

Some areaseries object properties that you set on an individual areaseries object set the values for all areaseries objects in the graph. See the property descriptions for information on specific properties.

Examples

Stacked Area Graph

This example plots the data in the variable Y as an area graph. Each subsequent column of Y is stacked on top of the previous data. The figure colormap controls the coloring of the individual areas. You can explicitly set the color of an area using the EdgeColor and FaceColor properties.

Y = [1, 5, 3;

    3, 2, 7;

    1, 5, 3;

    2, 6, 1];

area(Y)

grid on

colormap summer

set(gca,'Layer','top')

title 'Stacked Area Plot'

Adjusting the Base Value

The area function uses a y-axis value of 0 as the base of the filled areas. You can change this value by setting the area BaseValue property. For example, negate one of the values of Y from the previous example and replot the data.

Y(3,1) = -1; % Was 1

h = area(Y);

set(gca,'Layer','top')

grid on

colormap summer

Adjusting the BaseValue property improves the appearance of the graph:

set(h,'BaseValue',-2)

Setting the BaseValue property on one areaseries object sets the values of all objects

Specifying Colors and Line Styles

You can specify the colors of the filled areas and the type of lines used to separate them.

h = area(Y,-2); % Set BaseValue via argument

set(h(1),'FaceColor',[.5 0 0])

set(h(2),'FaceColor',[.7 0 0])

set(h(3),'FaceColor',[1 0 0])

set(h,'LineStyle',':','LineWidth',2) % Set all to same value

scatter

Scatter plot

Syntax

scatter(X,Y,S,C)
scatter(X,Y)
scatter(X,Y,S)
scatter(...,markertype)
scatter(...,'filled')
scatter(...,'PropertyName',propertyvalue)
scatter(axes_handle,...)
h = scatter(...)

Description

scatter(X,Y,S,C) displays colored circles at the locations specified by the vectors X and Y (which must be the same size).

S determines the area of each marker (specified in points^2). S can be a vector the same length as X and Y or a scalar. If S is a scalar, MATLAB draws all the markers the same size. If S is empty, the default size is used.

C determines the color of each marker. When C is a vector the same length as X and Y, the values in C are linearly mapped to the colors in the current colormap. When C is a 1-by-3 matrix, it specifies the colors of the markers as RGB values. If you have 3 points in the scatter plot and wish to have the colors be indices into the colormap, C should be a 3-by-1 matrix. C can also be a color string (see ColorSpec for a list of color string specifiers).

scatter(X,Y) draws the markers in the default size and color.

scatter(X,Y,S) draws the markers at the specified sizes (S) with a single color. This type of graph is also known as a bubble plot.

scatter(...,markertype) uses the marker type specified instead of 'o' (see LineSpec for a list of marker specifiers).

scatter(...,'filled') fills the markers.

scatter(...,'PropertyName',propertyvalue) creates the scatter graph, applying the specified property settings. See scattergroup properties for a description of properties.

scatter(axes_handle,...) plots into the axes object with handle axes_handle instead of the current axes object (gca).

h = scatter(...) returns the handle of the scattergroup object created.

Examples

load seamount

scatter(x,y,5,z)

% Vary the size of circles by inverse depth and fill them with dark red

    figure

    scatter(x,y,sqrt(-z/2),[.5 0 0],'filled')

    zoom(2)

quiver

Quiver or velocity plot

Syntax

quiver(x,y,u,v)
quiver(u,v)
quiver(...,scale)
quiver(...,LineSpec)
quiver(...,LineSpec,'filled')
quiver(...,'PropertyName',PropertyValue,...)
quiver(axes_handle,...)
h = quiver(...)

Description

A quiver plot displays velocity vectors as arrows with components (u,v) at the points (x,y).

For example, the first vector is defined by components u(1),v(1) and is displayed at the point x(1),y(1).

quiver(x,y,u,v) plots vectors as arrows at the coordinates specified in each corresponding pair of elements in x and y. The matrices x, y, u, and v must all be the same size and contain corresponding position and velocity components. However, x and y can also be vectors, as explained in the next section. By default, the arrows are scaled to just not overlap, but you can scale them to be longer or shorter if you want.

quiver(u,v) draws vectors specified by u and v at equally spaced points in the x-y plane.

quiver(...,scale) automatically scales the arrows to fit within the grid and then stretches them by the factor scale. scale = 2 doubles their relative length, and scale = 0.5 halves the length. Use scale = 0 to plot the velocity vectors without automatic scaling. You can also tune the length of arrows after they have been drawn by choosing the Plot Edit tool, selecting the quivergroup object, opening the Property Editor, and adjusting the Length slider.

quiver(...,LineSpec) specifies line style, marker symbol, and color using any valid LineSpec. quiver draws the markers at the origin of the vectors.

quiver(...,LineSpec,'filled') fills markers specified by LineSpec.

quiver(...,'PropertyName',PropertyValue,...) specifies property name and property value pairs for the quivergroup objects the function creates.

quiver(axes_handle,...) plots into the axes with the handle axes_handle instead of into the current axes (gca).

h = quiver(...) returns the handle to the quivergroup object.

Expanding x- and y-Coordinates

MATLAB expands x and y if they are not matrices. This expansion is equivalent to calling meshgrid to generate matrices from vectors:

[x,y] = meshgrid(x,y);

quiver(x,y,u,v)

In this case, the following must be true:

length(x) = n and length(y) = m, where [m,n] = size(u) = size(v).

The vector x corresponds to the columns of u and v, and vector y corresponds to the rows of u and v.

Examples

Showing the Gradient with Quiver Plots

Plot the gradient field of the function :

figure

[X,Y] = meshgrid(-2:.2:2);

Z = X.*exp(-X.^2 - Y.^2);

[DX,DY] = gradient(Z,.2,.2);

contour(X,Y,Z)

hold on

quiver(X,Y,DX,DY)

colormap hsv

hold off

quiver3

3-D quiver or velocity plot

Syntax

quiver3(x,y,z,u,v,w)
quiver3(z,u,v,w)
quiver3(...,scale)
quiver3(...,LineSpec)
quiver3(...,LineSpec,'filled')
quiver3(...,'PropertyName',PropertyValue,...)
quiver3(axes_handle,...)
h = quiver3(...)

Description

A three-dimensional quiver plot displays vectors with components (u,v,w) at the points (x,y,z), where u,v,w,x,y, and z all have real (non-complex) values.

quiver3(x,y,z,u,v,w) plots vectors with components (u,v,w) at the points (x,y,z). The matrices x,y,z,u,v,w must all be the same size and contain the corresponding position and vector components.

quiver3(z,u,v,w) plots the vectors at the equally spaced surface points specified by matrix z. quiver3 automatically scales the vectors based on the distance between them to prevent them from overlapping.

quiver3(...,scale) automatically scales the vectors to prevent them from overlapping, and then multiplies them by scale. scale = 2 doubles their relative length, and scale = 0.5 halves them. Use scale = 0 to plot the vectors without the automatic scaling.

quiver3(...,LineSpec) specifies line type and color using any valid LineSpec.

quiver3(...,LineSpec,'filled') fills markers specified by LineSpec.

quiver3(...,'PropertyName',PropertyValue,...) specifies property name and property value pairs for the quivergroup objects the function creates.

quiver3(axes_handle,...) plots into the axes with the handle axes_handle instead of into the current axes (gca).

h = quiver3(...) returns a vector of line handles.

Examples

Plot the surface normals of the function .

figure

[X,Y] = meshgrid(-2:0.25:2,-1:0.2:1);

Z = X.* exp(-X.^2 - Y.^2);

[U,V,W] = surfnorm(X,Y,Z);

quiver3(X,Y,Z,U,V,W,0.5);

hold on

surf(X,Y,Z);

colormap hsv

view(-35,45)

axis ([-2 2 -1 1 -.6 .6])

hold off

pie

Pie chart

Syntax

pie(X)
pie(X,explode)
pie(...,labels)
pie(axes_handle,...)
h = pie(...)

Description

pie(X) draws a pie chart using the data in X. Each element in X is represented as a slice in the pie chart.

pie(X,explode) offsets a slice from the pie. explode is a vector or matrix of zeros and nonzeros that correspond to X. A nonzero value offsets the corresponding slice from the center of the pie chart, so that X(i,j) is offset from the center if explode(i,j) is nonzero. explode must be the same size as X.

pie(...,labels) specifies text labels for the slices. The number of labels must equal the number of elements in X. For example,

pie(1:3,{'Taxes','Expenses','Profit'})

pie(axes_handle,...) plots into the axes with the handle axes_handle instead of into the current axes (gca).

h = pie(...) returns a vector of handles to patch and text graphics objects.

Tips

The values in X are normalized via X/sum(X) to determine the area of each slice of the pie. If sum(X) ≤ 1, the values in X directly specify the area of the pie slices. MATLAB draws only a partial pie if sum(X) < 1.

Examples

Emphasize the second slice in the chart by setting its corresponding explode element to 1.

x = [1 3 0.5 2.5 2];

explode = [0 1 0 0 0];

pie(x,explode)

colormap jet

pie3

3-D pie chart

Syntax

pie3(X)
pie3(X,explode)
pie3(...,labels)
pie3(axes_handle,...)
h = pie3(...)

Description

pie3(X) draws a three-dimensional pie chart using the data in X. Each element in X is represented as a slice in the pie chart.

pie3(X,explode) specifies whether to offset a slice from the center of the pie chart. X(i,j) is offset from the center of the pie chart if explode(i,j) is nonzero. explode must be the same size as X.

pie3(...,labels) specifies text labels for the slices. The number of labels must equal the number of elements in X. For example,

pie3(1:3,{'Taxes','Expenses','Profit'})

pie3(axes_handle,...) plots into the axes with the handle axes_handle instead of into the current axes (gca).

h = pie3(...) returns a vector of handles to patch, surface, and text graphics objects.

Tips

The values in X are normalized via X/sum(X) to determine the area of each slice of the pie. If sum(X) ≤ 1, the values in X directly specify the area of the pie slices. MATLAB draws only a partial pie if sum(X) < 1.

Examples

Offset a slice in the pie chart by setting the corresponding explode element to 1:

x = [1 3 0.5 2.5 2];

explode = [0 1 0 0 0];

pie3(x,explode)

colormap hsv

☆stem

Plot discrete sequence data

Syntax

stem(Y)
stem(X,Y)
stem(...,'fill')
stem(...,LineSpec)
stem(...,'PropertyName',PropertyValue,...)
stem(axes_handle,...)
h = stem(...)

Description

A two-dimensional stem plot displays data as lines extending from a baseline along the x-axis. A circle (the default) or other marker whose y-position represents the data value terminates each stem.

stem(Y) plots the data sequence Y as stems that extend from equally spaced and automatically generated values along the x-axis. When Y is a matrix, stem plots all elements in a row against the same x value.

stem(X,Y) plots X versus the columns of Y. X and Y must be vectors or matrices of the same size. Additionally, X can be a row or a column vector and Y a matrix with length(X) rows.

stem(...,'fill') specifies whether to color the circle at the end of the stem.

stem(...,LineSpec) specifies the line style, marker symbol, and color for the stem and top marker (the baseline is not affected). See LineSpec for more information.

stem(...,'PropertyName',PropertyValue,...) specifies property name and property value pairs for the stemseries objects the function creates.

stem(axes_handle,...) plots into the axes object with the handle axes_handle instead of into the current axes object (gca).

h = stem(...) returns a vector of stemseries object handles in h, one handle per column of data in Y.

Examples

Single Series of Data

This example creates a stem plot representing the cosine of 10 values linearly spaced between 0 and 2π. Note that the line style of the baseline is set by first getting its handle from the stemseries object's BaseLine property.

figure

t = linspace(-2*pi,2*pi,10);

h = stem(t,cos(t),'fill','--');

set(get(h,'BaseLine'),'LineStyle',':')

set(h,'MarkerFaceColor','red')

If you do not want the baseline to show, you can make the baseline invisible:

set(get(h,'Baseline'),'Visble','off')

where h is the stemseries handle returned by the stem function.

Delete the baseline with this command:

delete(get(h,'Baseline'))

Use similar code to change the color or style of the baseline, specifying any line property and value, for example,

set(get(h,'Baseline'),'LineWidth',3)

Two Series of Data on One Graph

This example creates a stem plot from a two-column matrix. In this case, the stem function creates two stemseries objects, one for each column of data. Both objects' handles are returned in the output argument h.

h(1) is the handle to the stemseries object plotting the expression exp(-.07*x).*cos(x).

h(2) is the handle to the stemseries object plotting the expression exp(.05*x).*cos(x).

figure

x = 0:25;

y = [exp(-.07*x).*cos(x);exp(.05*x).*cos(x)]';

h = stem(x,y);

set(h(1),'MarkerFaceColor','blue')

set(h(2),'MarkerFaceColor','red','Marker','square')

stairs

Stairstep graph

Syntax

stairs(Y)
stairs(X,Y)
stairs(...,LineSpec)
stairs(...,'PropertyName',propertyvalue)
stairs(axes_handle,...)
h = stairs(...)
[xb,yb] = stairs(Y,...)

Description

Stairstep graphs are useful for drawing time-history graphs of digitally sampled data.

stairs(Y) draws a stairstep graph of the elements of Y, drawing one line per column for matrices. The axes ColorOrder property determines the color of the lines.

When Y is a vector, the x-axis scale ranges from 1 to length(Y). When Y is a matrix, the x-axis scale ranges from 1 to the number of rows in Y.

stairs(X,Y) plots the elements in Y at the locations specified in X.

X must be the same size as Y or, if Y is a matrix, X can be a row or a column vector such that

length(X) = size(Y,1)

stairs(...,LineSpec) specifies a line style, marker symbol, and color for the graph. (See LineSpec for more information.)

stairs(...,'PropertyName',propertyvalue) creates the stairstep graph, applying the specified property settings. See Stairseries properties for a description of properties.

stairs(axes_handle,...) plots into the axes with the handle axes_handle instead of into the current axes object (gca).

h = stairs(...) returns the handles of the stairseries objects created (one per matrix column).

[xb,yb] = stairs(Y,...) does not draw graphs, but returns vectors xb and yb such that plot(xb,yb) plots the stairstep graph.

Examples

Create a stairstep plot of a sine wave.

x = linspace(-2*pi,2*pi,40);

stairs(x,sin(x))

☆ezcontour

Easy-to-use contour plotter

Syntax

ezcontour(fun)
ezcontour(fun,domain)
ezcontour(...,n)
ezcontour(axes_handle,...)
h = ezcontour(...)

Description

ezcontour(fun) plots the contour lines of fun(x,y) using the contour function. fun is plotted over the default domain: -2π < x < 2π, -2π < y < 2π.

fun can be a function handle for a MATLAB file function or an anonymous function (see Function Handles and Anonymous Functions) or a string (see Tips).

ezcontour(fun,domain) plots fun(x,y) over the specified domain. domain can be either a 4-by-1 vector [xmin, xmax, ymin, ymax] or a 2-by-1 vector [min, max] (where min < x < max, min < y < max).

ezcontour(...,n) plots fun over the default domain using an n-by-n grid. The default value for n is 60.

ezcontour(axes_handle,...) plots into the axes with handle axes_handle instead of the current axes (gca).

h = ezcontour(...) returns the handles to contour objects in h.

ezcontour automatically adds a title and axis labels

Tips

Passing the Function as a String

Array multiplication, division, and exponentiation are always implied in the string expression you pass to ezcontour. For example, the MATLAB syntax for a contour plot of the expression

sqrt(x.^2 + y.^2)

is written as

ezcontour('sqrt(x^2 + y^2)')

That is, x^2 is interpreted as x.^2 in the string you pass to ezcontour.

If the function to be plotted is a function of the variables u and v (rather than x and y), the domain endpoints umin, umax, vmin, and vmax are sorted alphabetically. Thus, ezcontour('u^2 - v^3',[0,1],[3,6]) plots the contour lines for u2 - v3 over 0 < u < 1, 3 < v < 6.

Passing a Function Handle

Function handle arguments must point to functions that use MATLAB syntax. For example, the following statements define an anonymous function and pass the function handle fh to ezcontour.

fh = @(x,y) sqrt(x.^2 + y.^2);

ezcontour(fh)

When using function handles, you must use the array power, array multiplication, and array division operators (.^, .*, ./) since ezcontour does not alter the syntax, as in the case with string inputs.

Passing Additional Arguments

If your function has additional parameters, for example, k in myfun:

function z = myfun(x,y,k)

z = x.^k - y.^k - 1;

then use an anonymous function to specify that parameter:

ezcontour(@(x,y)myfun(x,y,2))

Examples

The following mathematical expression defines a function of two variables, x and y.

ezcontour requires a function handle argument that expresses this function using MATLAB syntax. This example uses an anonymous function, which you can define in the command window without creating a separate file.

f=@(x,y) 3*(1-x).^2.*exp(-(x.^2) - (y+1).^2) ...

   - 10*(x/5 - x.^3 - y.^5).*exp(-x.^2-y.^2) ...

   - 1/3*exp(-(x+1).^2 - y.^2);

For convenience, this function is written on three lines. The MATLAB peaks function evaluates this expression for different sizes of grids.

Pass the function handle f to ezcontour along with a domain ranging from -3 to 3 in both x and y and specify a computational grid of 49-by-49:

ezcontour(f,[-3,3],49)

相关推荐