When You Start Matlab.docx

  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View When You Start Matlab.docx as PDF for free.

More details

  • Words: 15,409
  • Pages: 78
When you start MATLAB®, the desktop appears in its default layout.

The desktop includes these panels: 

Current Folder — Access your files.



Command Window — Enter commands at the command line, indicated by the prompt (>>).



Workspace — Explore data that you create or import from files.

As you work in MATLAB, you issue commands that create variables and call functions. For example, create a variable named a by typing this statement at the command line: a = 1 MATLAB adds variable a to the workspace and displays the result in the Command Window. a = 1 Create a few more variables. b = 2 b = 2 c = a + b c = 3 d = cos(a) d =

0.5403 When you do not specify an output variable, MATLAB uses the variable ans, short for answer, to store the results of your calculation. sin(a) ans = 0.8415 If you end a statement with a semicolon, MATLAB performs the computation, but suppresses the display of output in the Command Window. e = a*b; You can recall previous commands by pressing the up- and down-arrow keys, ↑ and ↓. Press the arrow keys either at an empty command line or after you type the first few characters of a command. For example, to recall the command b = 2, type b, and then press the up-arrow key.

Next in Getting Started with MATLAB

Matrices and Arrays Open Script

MATLAB is an abbreviation for "matrix laboratory." While other programming languages mostly work with numbers one at a time, MATLAB® is designed to operate primarily on whole matrices and arrays. All MATLAB variables are multidimensional arrays, no matter what type of data. A matrix is a two-dimensional array often used for linear algebra.

Array Creation To create an array with four elements in a single row, separate the elements with either a comma (,) or a space. a = [1 2 3 4] a = 1

2

3

This type of array is a row

4

vector.

To create a matrix that has multiple rows, separate the rows with semicolons. a = [1 2 3; 4 5 6; 7 8 10] a = 1 4 7

2 5 8

3 6 10

Another way to create a matrix is to use a function, such as ones, zeros, or rand. For example, create a 5-by-1 column vector of zeros. z = zeros(5,1)

z = 0 0 0 0 0

Matrix and Array Operations MATLAB allows you to process all of the values in a matrix using a single arithmetic operator or function. a + 10 ans = 11 14 17

12 15 18

13 16 20

sin(a) ans = 0.8415 -0.7568 0.6570

0.9093 -0.9589 0.9894

0.1411 -0.2794 -0.5440

To transpose a matrix, use a single quote ('): a' ans = 1 2 3

4 5 6

7 8 10

You can perform standard matrix multiplication, which computes the inner products between rows and columns, using the *operator. For example, confirm that a matrix times its inverse returns the identity matrix: p = a*inv(a) p = 1.0000 0 0

0 1.0000 0

-0.0000 0 1.0000

Notice that p is not a matrix of integer values. MATLAB stores numbers as floating-point values, and arithmetic operations are sensitive to small differences between the actual value and its floating-point representation. You can display more decimal digits using the format command: format long p = a*inv(a) p =

1.000000000000000 0 0

0 1.000000000000000 0

-0.000000000000000 0 0.999999999999998

Reset the display to the shorter format using format short format affects only the display of numbers, not the way MATLAB computes or saves them. To perform element-wise multiplication rather than matrix multiplication, use the .* operator: p = a.*a p = 1 16 49

4 25 64

9 36 100

The matrix operators for multiplication, division, and power each have a corresponding array operator that operates element-wise. For example, raise each element of a to the third power: a.^3 ans = 1 64 343

8 125 512

27 216 1000

Concatenation

Concatenation is the process of joining arrays to make larger ones. In fact, you made your first array by concatenating its individual elements. The pair of square brackets [] is the concatenation operator. A = [a,a] A = 1 4 7

2 5 8

3 6 10

1 4 7

2 5 8

3 6 10

Concatenating arrays next to one another using commas is called horizontal concatenation. Each array must have the same number of rows. Similarly, when the arrays have the same number of columns, you can concatenate vertically using semicolons. A = [a; a] A = 1 4 7 1 4 7

2 5 8 2 5 8

3 6 10 3 6 10

Complex Numbers Complex numbers have both real and imaginary parts, where the imaginary unit is the square root of -1. sqrt(-1) ans = 0.0000 + 1.0000i To represent the imaginary part of complex numbers, use either i or j . c = [3+4i, 4+3j; -i, 10j] c = 3.0000 + 4.0000i 0.0000 - 1.0000i

4.0000 + 3.0000i 0.0000 +10.0000i

Array Indexing Open Script Every variable in MATLAB® is an array that can hold many numbers. When you want to access selected elements of an array, use indexing. For example, consider the 4-by-4 magic square A: A = magic(4) A = 16 5 9 4

2 11 7 14

3 10 6 15

13 8 12 1

There are two ways to refer to a particular element in an array. The most common way is to specify row and column subscripts, such as A(4,2) ans = 14 Less common, but sometimes useful, is to use a single subscript that traverses down each column in order: A(8) ans = 14 Using a single subscript to refer to a particular element in an array is called linear indexing.

If you try to refer to elements outside an array on the right side of an assignment statement, MATLAB throws an error. test = A(4,5) Index exceeds matrix dimensions. However, on the left side of an assignment statement, you can specify elements outside the current dimensions. The size of the array increases to accommodate the newcomers. A(4,5) = 17 A = 16 5 9 4

2 11 7 14

3 10 6 15

13 8 12 1

0 0 0 17

To refer to multiple elements of an array, use the colon operator, which allows you to specify a range of the form start:end. For example, list the elements in the first three rows and the second column of A: A(1:3,2) ans = 2 11 7 The colon alone, without start or end values, specifies all of the elements in that dimension. For example, select all the columns in the third row of A: A(3,:) ans = 9

7

6

12

0

The colon operator also allows you to create an equally spaced vector of values using the more general form start:step:end. B = 0:10:100 B = 0

10

20

30

40

50

60

70

80

90

100

If you omit the middle step, as in start:end, MATLAB uses the default step value of 1.

Workspace Variables The workspace contains variables that you create within or import into MATLAB ® from data files or other programs. For example, these statements create variables A and B in the workspace. A = magic(4); B = rand(3,5,2);

You can view the contents of the workspace using whos. whos Name

Size

A B

4x4 3x5x2

Bytes 128 240

Class

Attributes

double double

The variables also appear in the Workspace pane on the desktop.

Workspace variables do not persist after you exit MATLAB. Save your data for later use with the save command, save myfile.mat Saving preserves the workspace in your current working folder in a compressed file with a .mat extension, called a MAT-file. To clear all the variables from the workspace, use the clear command. Restore data from a MAT-file into the workspace using load. load myfile.mat

Next in Getting Started with MATLAB Text and Characters

Text and Characters Open Script When you are working with text, enclose sequences of characters in single quotes. You can assign text to a variable. myText = 'Hello, world'; If the text includes a single quote, use two single quotes within the definition. otherText = 'You''re right' otherText = You're right myText and otherText are arrays, like all MATLAB® variables. Their class or data type is char, which is short for character. whos myText Name

Size

Bytes

Class

Attributes

myText

1x12

24

char

You can concatenate character arrays with square brackets, just as you concatenate numeric arrays. longText = [myText,' - ',otherText] longText = Hello, world - You're right To convert numeric values to characters, use functions, such as num2str or int2str. f = 71; c = (f-32)/1.8; tempText = ['Temperature is ',num2str(c),'C'] tempText = Temperature is 21.6667C

Next in Getting Started with MATLAB Calling Functions

Calling Functions Open Script MATLAB® provides a large number of functions that perform computational tasks. Functions are equivalent to subroutines or methods in other programming languages. To call a function, such as max, enclose its input arguments in parentheses: A = [1 3 5]; max(A) ans = 5 If there are multiple input arguments, separate them with commas: B = [10 6 4]; max(A,B) ans = 10

6

5

Return output from a function by assigning it to a variable: maxA = max(A) maxA = 5

When there are multiple output arguments, enclose them in square brackets: [maxA,location] = max(A) maxA = 5

location = 3 Enclose any character inputs in single quotes: disp('hello world') hello world To call a function that does not require any inputs and does not return any outputs, type only the function name: clc The clc function clears the Command Window.

Next in Getting Started with MATLAB 2-D and 3-D Plots

  



Documentation Home

 

MATLAB Getting Started with MATLAB

     

2-D and 3-D Plots

Trial Software Product Updates

Translate This Page

ON THIS PAGE Line Plots 3-D Plots Subplots Next in Getting Started with MATLAB

2-D and 3-D Plots Line Plots Open Script To create two-dimensional line plots, use the plot function. For example, plot the value of the sine function from 0 to : x = 0:pi/100:2*pi; y = sin(x); plot(x,y)

You can label the axes and add a title. xlabel('x') ylabel('sin(x)') title('Plot of the Sine Function')

By adding a third input argument to the plot function, you can plot the same variables using a red dashed line. plot(x,y,'r--')

The 'r--' string is a line specification. Each specification can include characters for the line color, style, and marker. A marker is a symbol that appears at each plotted data point, such as a +, o, or *. For example, 'g:*' requests a dotted green line with * markers. Notice that the titles and labels that you defined for the first plot are no longer in the current figure window. By default, MATLAB® clears the figure each time you call a plotting function, resetting the axes and other elements to prepare the new plot. To add plots to an existing figure, use hold. x = 0:pi/100:2*pi; y = sin(x); plot(x,y) hold on y2 = cos(x); plot(x,y2,':') legend('sin','cos')

Until you use hold off or close the window, all plots appear in the current figure window.

3-D Plots Open Script Three-dimensional plots typically display a surface defined by a function in two variables, z = f(x,y) . To evaluate z, first create a set of (x,y) points over the domain of the function using meshgrid. [X,Y] = meshgrid(-2:.2:2); Z = X .* exp(-X.^2 - Y.^2); Then, create a surface plot. surf(X,Y,Z)

Both the surf function and its companion mesh display surfaces in three dimensions. surf displays both the connecting lines and the faces of the surface in color. mesh produces wireframe surfaces that color only the lines connecting the defining points.

Subplots Open Script You can display multiple plots in different subregions of the same window using the subplot function. The first two inputs to subplot indicate the number of plots in each row and column. The third input specifies which plot is active. For example, create four plots in a 2-by-2 grid within a figure window. t = 0:pi/10:2*pi; [X,Y,Z] = cylinder(4*cos(t)); subplot(2,2,1); mesh(X); title('X'); subplot(2,2,2); mesh(Y); title('Y'); subplot(2,2,3); mesh(Z); title('Z'); subplot(2,2,4); mesh(X,Y,Z); title('X,Y,Z');

Next in Getting Started with MATLAB Programming and Scripts

  

  

Documentation Home



Programming and Scripts

    

ON THIS PAGE

Trial Software Product Updates

Translate This Page

MATLAB Getting Started with MATLAB

Sample Script Loops and Conditional Statements Script Locations Next in Getting Started with MATLAB

Programming and Scripts The simplest type of MATLAB® program is called a script. A script is a file with a .m extension that contains multiple sequential lines of MATLAB commands and function calls. You can run a script by typing its name at the command line. Sample Script To create a script, use the edit command, edit plotrand

This opens a blank file named plotrand.m. Enter some code that plots a vector of random data: n = 50; r = rand(n,1); plot(r)

Next, add code that draws a horizontal line on the plot at the mean: m = mean(r); hold on plot([0,n],[m,m]) hold off title('Mean of Random Uniform Data')

Whenever you write code, it is a good practice to add comments that describe the code. Comments allow others to understand your code, and can refresh your memory when you return to it later. Add comments using the percent ( %) symbol. % Generate random data from a uniform distribution % and calculate the mean. Plot the data and the mean. n = 50; r = rand(n,1); plot(r)

% 50 data points

% Draw a line from (0,m) to (n,m) m = mean(r); hold on plot([0,n],[m,m]) hold off title('Mean of Random Uniform Data')

Save the file in the current folder. To run the script, type its name at the command line: plotrand

You can also run scripts from the Editor by pressing the Run button,

.

Loops and Conditional Statements Within a script, you can loop over sections of code and conditionally execute sections using the keywords for, while, if, and switch. For example, create a script named calcmean.m that uses a for loop to calculate the mean of five random samples and the overall mean. nsamples = 5; npoints = 50; for k = 1:nsamples currentData = rand(npoints,1); sampleMean(k) = mean(currentData); end overallMean = mean(sampleMean)

Now, modify the for loop so that you can view the results at each iteration. Display text in the Command Window that includes the current iteration number, and remove the semicolon from the assignment to sampleMean. for k = 1:nsamples

iterationString = ['Iteration #',int2str(k)]; disp(iterationString) currentData = rand(npoints,1); sampleMean(k) = mean(currentData) end overallMean = mean(sampleMean)

When you run the script, it displays the intermediate results, and then calculates the overall mean. calcmean Iteration #1 sampleMean = 0.3988 Iteration #2 sampleMean = 0.3988

0.4950

Iteration #3 sampleMean = 0.3988

0.4950

0.5365

0.4950

0.5365

0.4870

0.4950

0.5365

0.4870

Iteration #4 sampleMean = 0.3988 Iteration #5 sampleMean = 0.3988

0.5501

overallMean = 0.4935

In the Editor, add conditional statements to the end of calcmean.m that display a different message depending on the value of overallMean. if overallMean < .49 disp('Mean is less than expected') elseif overallMean > .51 disp('Mean is greater than expected') else disp('Mean is within the expected range') end

Run calcmean and verify that the correct message displays for the calculated overallMean. For example:

overallMean = 0.5178 Mean is greater than expected

Script Locations MATLAB looks for scripts and other files in certain places. To run a script, the file must be in the current folder or in a folder on the search path. By default, the MATLAB folder that the MATLAB Installer creates is on the search path. If you want to store and run programs in another folder, add it to the search path. Select the folder in the Current Folder browser, right-click, and then select Add to Path.

Next in Getting Started with MATLAB Help and Documentation

Help and Documentation All MATLAB® functions have supporting documentation that includes examples and describes the function inputs, outputs, and calling syntax. There are several ways to access this information from the command line: 

Open the function documentation in a separate window using the doc command. doc mean



Display function hints (the syntax portion of the function documentation) in the Command Window by pausing after you type the open parentheses for the function input arguments. mean(



View an abbreviated text version of the function documentation in the Command Window using the help command. help mean Access the complete product documentation by clicking the help icon

.

 

Entering Commands





Documentation Home

 

MATLAB Language Fundamentals

    

Entering Commands Matrices and Arrays Operators and Elementary Operations Special Characters Data Types

Trial Software Product Updates

Translate This Page

Build and run MATLAB® statements

Functions ans

Most recent answer

clc

Clear Command Window

diary

Save Command Window text to file

format

Set Command Window output display format

home

Send cursor home

iskeyword

Determine whether input is MATLAB keyword

more

Control paged output for Command Window

Examples and How To Enter Statements in Command Window Enter individual statements in the Command Window while working in MATLAB. Format Output MATLAB displays output in both the Command Window and the Live Editor. You can format the output display using several provided options. Call Functions These examples show the syntax to call a MATLAB function. Continue Long Statements on Multiple Lines Extend long program lines using ellipses (...). Create Shortcuts to Rerun Commands A MATLAB shortcut is an easy way to run a group of MATLAB language statements that you use regularly. Stop Execution Stop the execution of a MATLAB command. Find Functions to Use Find the name and description of a MathWorks® function from the Command Window or Editor using the Function browser. Find Text in Command Window or History Search text currently in the Command Window or Command History Window. Check Syntax as You Type Some entries appear in different colors in the Command Window and the Editor to help you identify MATLAB elements. This is known as syntax highlighting. Write to a Diary File To keep an activity log of your MATLAB session, use the diary function.

Concepts

Variable Names Create valid variable names and avoid potential naming conflicts. Case and Space Sensitivity MATLAB code is sensitive to casing, and insensitive to blank spaces except when defining arrays. Command vs. Function Syntax If you do not require any outputs from a function, and all of the inputs are character vectors, you can use command syntax. With command syntax, you omit parentheses in the function call and separate the inputs with spaces. Command History The Command History window displays a log of statements that you ran in the current and previous MATLAB sessions. Set Command Window Preferences Specify appearance of Command Window and its output. Set Keyboard Preferences Settings for Tab completion, function hints, and delimiter matching.

Troubleshooting Common Errors When Calling Functions Troubleshoot error message related to calling functions.

Enter Statements in Command Window As you work in MATLAB®, you can enter individual statements in the Command Window. For example, create a variable named a by typing this statement at the command line: a = 1 MATLAB immediately adds variable a to the workspace and displays the result in the Command Window. a = 1 When you do not specify an output variable, MATLAB uses the variable ans, short for answer, to store the results of your calculation. sin(a) ans = 0.8415 The value of ans changes with every command that returns an output value that is not assigned to a variable.

If you end a statement with a semicolon, MATLAB performs the computation, but suppresses the display of output in the Command Window. b = 2; To enter multiple statements on multiple lines before running any of the statements, use Shift+Enter between statements. This action is unnecessary when you enter a paired keyword statement on multiple lines, such as for and end. You also can enter more than one statement on the same line by separating statements. To distinguish between commands, end each one with a comma or semicolon. Commands that end with a comma display their results, while commands that end with a semicolon do not. For example, enter the following three statements at the command line: A = magic(5),

B = ones(5) * 4.7;

C = A./B

A = 17 23 4 10 11

24 5 6 12 18

1 7 13 19 25

8 14 20 21 2

15 16 22 3 9

C = 3.6170 4.8936 0.8511 2.1277 2.3404

5.1064 1.0638 1.2766 2.5532 3.8298

0.2128 1.4894 2.7660 4.0426 5.3191

1.7021 2.9787 4.2553 4.4681 0.4255

3.1915 3.4043 4.6809 0.6383 1.9149

MATLAB displays only the values of A and C in the Command Window. To recall previous lines in the Command Window, press the up- and down-arrow keys, ↑ and ↓. Press the arrow keys either at an empty command line or after you type the first few characters of a command. For example, to recall the command b = 2, type b, and then press the up-arrow key. To clear a command from the Command Window without executing it, press the Escape (Esc) key. You can evaluate any statement already in the Command Window. Select the statement, rightclick, and then select Evaluate Selection. In the Command Window, you also can execute only a portion of the code currently at the command prompt. To evaluate a portion of the entered code, select the code, and then press Enter. For example, select a portion of the following code:

hello

Format Output MATLAB® displays output in both the Command Window and the Live Editor. You can format the output display using several provided options. 

Format Line Spacing in Output



Format Floating-Point Numbers



Wrap Lines of Code to Fit Window Width



Suppress Output



View Output by Page



Clear the Command Window

Format Line Spacing in Output By default, MATLAB displays blanks lines in command window output. You can select one of two numeric display options in MATLAB. 

loose — Keeps the display of blank lines (default). 

>> x = [4/3 1.2345e-6]

 

x =

 1.3333 

0.0000

compact — Suppresses the display of blank lines. 

>> x = [4/3 1.2345e-6]



x = 1.3333

0.0000

To format the output display, do one of the following: 

On the Home tab, in the Environment section, click Preferences. Select MATLAB > Command Window, and then choose a Numeric display option.



Use the format function at the command line, for example:



format loose format compact Note: Line spacing display options do not apply in the Live Editor.

Format Floating-Point Numbers You can change the way numbers display in both the Command Window and the Live Editor. By default, MATLAB uses the short format (5-digit scaled, fixed-point values). For example, suppose that you enter x = [4/3 1.2345e-6] in the Command Window. The MATLAB output display depends on the format you selected. This table shows some of the available numeric display formats, and their corresponding output. Numeric Display Format

Example Output

short (default)

x = 1.3333 0.0000

short e

x = 1.3333e+00 1.2345e-06

long

x = 1.333333333333333 0.000001234500000

+

x = ++

Note: The text display format affects only how numbers are shown, not how MATLAB computes, or saves them.

To format the way numbers display, do one of the following: 

On the Home tab, in the Environment section, click Preferences. Select MATLAB > Command Window, and then choose a Numeric format option.



Use the format function, for example:

 

format short format short e format long See the format reference page for a list and description of all supported numeric formats.

Wrap Lines of Code to Fit Window Width A line of code or its output can exceed the width of the Command Window, requiring you to use the horizontal scroll bar to view the entire line. To break a single line of input or output into multiple lines to fit within the current width of the Command Window: 1. On the Home tab, in the Environment section, click Select MATLAB > Command Window.

Preferences.

2. Select Wrap Lines. 3. Click OK. Note: Line wrapping options do not apply in the Live Editor.

Suppress Output To suppress code output, add a semicolon (;) to the end of a command. This is useful when code generates large matrices. Running the following code creates A, but does not show the resulting matrix in the Command Window or the Live Editor: A = magic(100);

View Output by Page Output in the Command Window might exceed the visible portion of the window. You can view the output, one screen at a time: 1. In the Command Window, type more on to enable paged output. 2. Type the command that generates large output. 3. View the output: 

Advance to the next line by pressing Enter.



Advance to the next page by pressing Space Bar.



Stop displaying the output by pressing q.

To disable paged output, type more off. Note: Paged output options do not apply in the Live Editor.

Clear the Command Window If the Command Window seems cluttered, you can clear all the text (without clearing the workspace) by doing one of the following: 

On the Home tab, in the Code section, select Clear Commands > Command Window to clear the Command Window scroll buffer.



Use the clc function to clear the Command Window scroll buffer.



Use the home function to clear your current view of the Command Window, without clearing the scroll buffer.

See Also clc | format | home | more

clc

Clear Command Window

Syntax clc

Description clc clears all input and output from the Command Window display, giving you a "clean screen." After using clc, you cannot use the scroll bar to see the history of functions, but you still can use the up arrow key, ↑, to recall statements from the command history.

Examples Use clc in a MATLAB® code file to always display output in the same starting position on the screen.

See Also clear | clf | close | home Introduced before R2006a

clf Clear current figure window

Syntax clf clf('reset') clf(fig) clf(fig,'reset') figure_handle = clf(...)

Description clf deletes from the current figure all graphics objects whose handles are not hidden (i.e., their HandleVisibilityproperty is set to on). clf('reset') deletes from the current figure all graphics objects regardless of the setting of their HandleVisibilityproperty and resets all figure properties except Position, Units, PaperPosition, and PaperUnits to their default values. clf(fig) or clf(fig,'reset') clears the single figure with handle fig. figure_handle = clf(...) returns the handle of the figure. This is useful when the figure IntegerHandle property is off because the noninteger handle becomes invalid when the reset option is used (i.e., IntegerHandle is reset to on, which is the default).

Alternatives Use Clear Figure from the figure window's Edit menu to clear the contents of a figure. You can also create a desktop shortcut to clear the current figure with one mouse click. See Create Shortcuts to Rerun Commands.

More About collapse all

Tips The clf command behaves the same way when issued on the command line as it does in callback routines — it does not recognize the HandleVisibility setting of callback. This means that when issued from within a callback routine, clf deletes only those objects whose HandleVisibility property is set to on.

See Also cla | clc | hold | reset Introduced before R2006a   

Trial Software Product Updates

Translate This Page



Documentation Home

         

MATLAB Graphics Formatting and Annotation Axes Appearance MATLAB Graphics Graphics Objects Specifying Target for Graphics Output MATLAB Functions

       

hold ON THIS PAGE Syntax Description Examples Input Arguments More About See Also

hold Retain current plot when adding new plots collapse all in page

Syntax 

hold on



hold off



hold all



hold



hold(ax,'on')



hold(ax,'off')



hold(ax)

example

example

Description example

hold on retains plots in the current axes so that new plots added to the axes do not delete existing plots. New plots use the next colors and line styles based on the ColorOrder and LineStyleOrder properties of the axes. MATLAB® adjusts axes limits, tick marks, and tick labels to display the full range of data. hold off sets the hold state to off so that new plots added to the axes clear existing plots and reset all axes properties. The next plot added to the axes uses the first color and line style based on the ColorOrderand LineStyleOrder properties of the axes. This is the default behavior. hold all is the same as hold on. Note: This syntax will be removed in a future release. Use hold on instead.

hold toggles the hold state between on and off. example

hold(ax,'on') sets the hold state to on for the axes specified by ax instead of the current axes. hold(ax,'off') sets the hold state to off for the specified axes. hold(ax) toggles the hold state for the specified axes.

Examples collapse all

Add Line Plot to Existing Graph

Open Script Create a line plot. Then, use hold on to add a second line plot without deleting the existing plot. The new plot uses the next color and line style based on the ColorOrder and LineStyleOrder properties of the axes. x = linspace(-pi,pi); y1 = sin(x); y2 = cos(x); plot(x,y1) hold on plot(x,y2)

Reset the hold state to off so that new plots delete existing plots. New plots start from the beginning of the color order and line style order. hold off y3 = sin(2*x); plot(x,y3)

Specify Hold State for Specific Axes

Open Script Create a figure with two subplots and add a line plot to each subplot. ax1 = subplot(2,1,1); x = linspace(0,2*pi); y1 = sin(x); plot(x,y1) ax2 = subplot(2,1,2); y2 = cos(x); plot(x,y2)

Add a second line plot to the upper subplot. hold(ax1,'on') y3 = sin(2*x); plot(ax1,x,y3)

Reset the hold state to off for the upper subplot so that new plots replace the existing plots, which is the default behavior. hold(ax1,'off') y4 = sin(4*x); plot(ax1,x,y4)

Input Arguments collapse all

ax — Axes object axes object Axes object. Use ax to set the hold state for a specific axes, instead of the current axes.

More About collapse all

Tips 

Use the ishold function to test the hold state.



The hold function toggles the NextPlot property of the axes between 'add' and 'replace'.



If an axes does not exist, then the hold command creates one.

See Also axes | cla | figure | ishold | newplot | subplot Introduced before R2006a

axes Create axes graphics object collapse all in page

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

Properties For a list of properties, see Axes Properties.

Description axes creates an axes graphics object in the current figure using default property values. axes is the low-level function for creating axes graphics objects. MATLAB® automatically creates an axes, if one does not already exist, when you issue a command that creates a graph. axes('PropertyName',propertyvalue,...) creates an axes object having the specified property values. For a description of the properties, see Axes Properties. MATLAB uses default values for any properties that you do not explicitly define as arguments. The axes function accepts property name/property value pairs, structure arrays, and cell arrays as input arguments (see the set and get commands for examples of how to specify these data types). While the basic purpose of an axes object is to provide a coordinate system for plotted data, axes properties provide considerable control over the way MATLAB displays data. axes(parent,...) creates the axes in the figure, uipanel, or uitab specified by parent, instead of in the current figure. axes(h) makes existing axes h the current axes and brings the figure containing it into focus. It also makes h the first axes listed in the figure's Children property and sets the figure's CurrentAxes property to h. The current axes is the target for functions that draw image, line, patch, rectangle, surface, and text graphics objects. If you want to make an axes the current axes without changing the state of the parent figure, set the CurrentAxes property of the figure containing the axes: set(figure_handle,'CurrentAxes',axes_handle) This command is useful if you want a figure to remain minimized or stacked below other figures, but want to specify the current axes. h = axes(...) returns the handle of the created axes object. Use the set function to modify the properties of an existing axes or the get function to query the current values of axes properties. Use the gca command to obtain the handle of the current axes. The axis (not axes) function provides simplified access to commonly used properties that control the scaling and appearance of axes. Set default axes properties on the figure and root levels: set(groot,'DefaultAxesPropertyName',PropertyValue,...) set(gcf,'DefaultAxesPropertyName',PropertyValue,...) PropertyName is the name of the axes property and PropertyValue is the value you are specifying. Use set and get to access axes properties.

Stretch-to-Fill By default, MATLAB stretches the axes to fill the axes position rectangle (the rectangle defined by the last two elements in the Position property). This results in graphs that use the available space in the rectangle. However, some 3-D graphs (such as a sphere) appear distorted because of this stretching, and are better viewed with a specific three-dimensional aspect ratio. Stretch-to-fill is active when the DataAspectRatioMode, PlotBoxAspectRatioMode, and CameraViewAngleMode are all auto (the default). However, stretch-to-fill is turned off when the DataAspectRatio, PlotBoxAspectRatio, or CameraViewAngle is user-specified, or when one or more of the corresponding modes is set to manual (which happens automatically when you set the corresponding property value). This picture shows the same sphere displayed both with and without the stretch-to-fill. The dotted lines show the axes rectangle.

When stretch-to-fill is disabled, MATLAB sets the size of the axes to be as large as possible within the constraints imposed by the Position rectangle without introducing distortion. In the picture above, the height of the rectangle constrains the axes size.

Examples collapse all

Position Multiple Axes in Figure

Open Script Create a figure with two axes. Specify the position of the first axes so that it has a lower left corner at the point (0.1 0.1) with a width and height of 0.7. Specify the position of the second axes so that it has a lower left corner at the point (0.65 0.65) with a width and height of 0.28. By default, the values are normalized to the figure. Return the axes objects as ax1 and ax2. figure ax1 = axes('Position',[0.1 0.1 0.7 0.7]); ax2 = axes('Position',[0.65 0.65 0.28 0.28]);

Add a plot to each axes. Specify the axes for the plot by passing the axes object as the first input argument to the graphics function. Most graphics functions reset some axes properties, such as the tick values and labels. However, they do not reset the axes position. contour(ax1,peaks(20)) surf(ax2,peaks(20))

Alternatives To create a figure select New > Figure from the figure window File menu. To add an axes to a figure, click one of the New Subplots icons in the Figure Palette, and slide right to select an arrangement of new axes. For details, see Customize Graph Using Plot Tools.

See Also Functions 

axis | cla | clf | figure | gca | grid | subplot | title | view | xlabel | ylabel | zlabel

Properties 

Axes Properties Introduced before R2006a

Axes Properties Control axes appearance and behavior expand all in page

Axes properties control the appearance and behavior of an axes object. By changing property values, you can modify certain aspects of the axes. Starting in R2014b, you can use dot notation to query and set properties. ax = gca; c = ax.Color;

ax.Color = 'blue'; If you are using an earlier release, use the get and set functions instead. Appearance expand all

Color — Color of axes back planes [1 1 1] (default) | RGB triplet | character vector | 'none' Box — Axes box outline 'off' (default) | 'on' BoxStyle — Style of axes box outline 'back' (default) | 'full' LineWidth — Width of axes outline, tick marks, and grid lines 0.5 (default) | scalar value Individual Axis Appearance and Scale expand all

XAxis, YAxis, ZAxis — Component that controls appearance and behavior of each axis numeric ruler object | datetime ruler object | duration ruler object XAxisLocation — Location of x-axis 'bottom' (default) | 'top' | 'origin' YAxisLocation — Location of y-axis 'left' (default) | 'right' | 'origin' XColor, YColor, ZColor — Color of axis line, tick values, and labels [0.15 0.15 0.15] (default) | RGB triplet | character vector | 'none' XColorMode, YColorMode, ZColorMode — Selection mode for axis line color 'auto' (default) | 'manual' XDir, YDir, ZDir — Direction of increasing values along axis 'normal' (default) | 'reverse' XScale, YScale, ZScale — Scale of values along axis 'linear' (default) | 'log' XLim, YLim, ZLim — Minimum and maximum axis limits [0 1] (default) | two-element vector of the form [min max] XLimMode, YLimMode, ZLimMode — Selection mode for axis limits 'auto' (default) | 'manual' Tick Values and Labels expand all

XTick, YTick, ZTick — Tick mark locations [] (default) | vector of increasing values XTickMode, YTickMode, ZTickMode — Selection mode for tick mark locations 'auto' (default) | 'manual' XTickLabel, YTickLabel, ZTickLabel — Tick mark labels '' (default) | cell array of character vectors | string array XTickLabelMode, YTickLabelMode, ZTickLabelMode — Selection mode for tick mark labels 'auto' (default) | 'manual' TickLabelInterpreter — Interpretation of characters in tick labels 'tex' (default) | 'latex' | 'none'

XTickLabelRotation, YTickLabelRotation, ZTickLabelRotation — Rotation of tick labels 0 (default) | scalar value in degrees XMinorTick, YMinorTick, ZMinorTick — Display of minor tick marks 'off' | 'on' TickLength — Tick mark length [0.01 0.025] (default) | two-element vector TickDir — Tick mark direction 'in' (default) | 'out' | 'both' TickDirMode — Selection mode for TickDir 'auto' (default) | 'manual' Grid Lines expand all

XGrid, YGrid, ZGrid — Display of grid lines 'off' (default) | 'on' XMinorGrid, YMinorGrid, ZMinorGrid — Display of minor grid lines 'off' (default) | 'on' GridLineStyle — Line style for grid lines '-' (default) | '--' | ':' | '-.' | 'none' MinorGridLineStyle — Line style for minor grid lines ':' (default) | '-' | '--' | '-.' | 'none' GridColor — Color of grid lines [0.15 0.15 0.15] (default) | RGB triplet | character vector | 'none' GridColorMode — Selection mode for GridColor 'auto' (default) | 'manual' MinorGridColor — Color of minor grid lines [0.1 0.1 0.1] (default) | RGB triplet | character vector MinorGridColorMode — Selection mode for MinorGridColor 'auto' (default) | 'manual' GridAlpha — Grid-line transparency 0.15 (default) | value in the range [0,1] GridAlphaMode — Selection mode for GridAlpha 'auto' (default) | 'manual' MinorGridAlpha — Minor grid line transparency 0.25 (default) | value in the range [0,1] MinorGridAlphaMode — Selection mode for MinorGridAlpha 'auto' (default) | 'manual' Layer — Placement of grid lines and tick marks in relation to graphic objects 'bottom' (default) | 'top' Font Style expand all

FontName — Font name system supported font name | 'FixedWidth' FontSize — Font size 10 (default) | scalar numeric value

TitleFontSizeMultiplier — Scale factor for title font size 1.1 (default) | numeric value greater than 0 LabelFontSizeMultiplier — Scale factor for label font size 1.1 (default) | numeric value greater than 0 FontUnits — Font size units 'points' (default) | 'inches' | 'centimeters' | 'characters' | 'normalized' | 'pixels' FontAngle — Character slant 'normal' (default) | 'italic' FontWeight — Thickness of text characters 'normal' (default) | 'bold' TitleFontWeight — Thickness of title text 'bold' (default) | 'normal' FontSmoothing — Text smoothing 'on' (default) | 'off' Title, Axis Labels, and Legend expand all

Title — Text object for axes title text object (default) XLabel, YLabel, ZLabel — Text object for axis label text object (default) Legend — Legend associated with axes empty GraphicsPlaceholder (default) | legend object Line Colors and Line Styles expand all

ColorOrder — Colors for multiline plots seven predefined colors (default) | three-column matrix of RGB triplets ColorOrderIndex — Next color to use in color order 1 (default) | positive integer LineStyleOrder — Line styles and markers for multiline plots '-' solid line (default) | cell array of line styles LineStyleOrderIndex — Next line style to use in line style order 1 (default) | positive integer Color and Transparency Mapping expand all

CLim — Color limits for objects using colormap [0 1] (default) | two-element vector of the form [cmin cmax] CLimMode — Selection mode for CLim 'auto' (default) | 'manual' ALim — Alpha limits for images, patches, and surfaces with transparency [0 1] (default) | two-element vector of the form [amin amax] ALimMode — Selection mode for ALim 'auto' (default) | 'manual' AmbientLightColor — Background light color [1 1 1] (default) | RGB triplet | character vector | 'none' Multiple Plots

expand all

NextPlot — Properties to reset when adding new plot 'replace' (default) | 'add' | 'replacechildren' | 'replaceall' SortMethod — Order for rendering objects 'depth' (default) | 'childorder' Visibility expand all

Visible — State of visibility 'on' (default) | 'off' Clipping — Clipping of objects to axes limits 'on' (default) | 'off' ClippingStyle — Boundaries used for clipping '3dbox' (default) | 'rectangle' Location and Size expand all

Position — Size and position of axes within figure or uipanel [0.1300 0.1100 0.7750 0.8150] (default) | four-element vector TightInset — Margins for text labels four-element vector of the form [left bottom right top] OuterPosition — Size and location of axes, including labels and margins [0 0 1 1] (default) | four-element vector ActivePositionProperty — Position property to hold constant during resize operation 'outerposition' (default) | 'position' Units — Position units 'normalized' (default) | 'inches' | 'centimeters' | 'points' | 'pixels' | 'characters' Aspect Ratio expand all

Projection — Type of projection onto 2-D screen 'orthographic' (default) | 'perspective' DataAspectRatio — Relative length of data units along each axis [1 1 1] (default) | three-element vector of the form [dx dy dz] DataAspectRatioMode — Selection mode for DataAspectRatio 'auto' (default) | 'manual' PlotBoxAspectRatio — Relative length of each axis [1 1 1] (default) | three-element vector of the form [px py pz] PlotBoxAspectRatioMode — Selection mode for PlotBoxAspectRatio 'auto' (default) | 'manual' View expand all

CameraPosition — Location of camera three-element vector of the form [x y z] CameraPositionMode — Selection mode for CameraPosition 'auto' (default) | 'manual' CameraTarget — Point used as camera target three-element vector of the form [x y z]

CameraTargetMode — Selection mode for CameraTarget 'auto' (default) | 'manual' CameraUpVector — Vector defining upwards direction [0 1 0] (default for 2-D view) | [0 0 1] (default for 3-D view) | three-element direction vector of the form [x y z] CameraUpVectorMode — Selection mode for CameraUpVector 'auto' (default) | 'manual' CameraViewAngle — Field of view 6.6086 (default) | scalar angle in range [0,180) CameraViewAngleMode — Selection mode for CameraViewAngle 'auto' (default) | 'manual' View — Azimuth and elevation of view [0 90] (default) | two-element vector of the form [azimuth elevation] Identifiers expand all

Type — Type of graphics object 'axes' Tag — Tag to associate with axes '' (default) | character vector UserData — Data to associate with axes [] (default) | any MATLAB data Parent/Child expand all

Parent — Parent of axes figure object | uipanel object | uitab object Children — Children of axes empty GraphicsPlaceholder array | array of graphics objects HandleVisibility — Visibility of object handle 'on' (default) | 'off' | 'callback' Interactive Control expand all

CurrentPoint — Location of mouse pointer 2-by-3 array ButtonDownFcn — Mouse-click callback '' (default) | function handle | cell array | character vector UIContextMenu — Context menu uicontextmenu object Selected — Selection state 'off' (default) | 'on' SelectionHighlight — Display of selection handles when selected 'on' (default) | 'off' Callback Execution Control expand all

PickableParts — Ability to capture mouse clicks 'visible' (default) | 'all' | 'none'

HitTest — Response to captured mouse clicks 'on' (default) | 'off' Interruptible — Callback interruption 'on' (default) | 'off' BusyAction — Callback queuing 'queue' (default) | 'cancel' Creation and Deletion Control expand all

CreateFcn — Creation callback '' (default) | function handle | cell array | character vector DeleteFcn — Deletion callback '' (default) | function handle | cell array | character vector BeingDeleted — Deletion status of axes 'off' (default) | 'on'

See Also axes | axis | box | caxis | cla | gca | grid

More About 

Access Property Values



Graphics Object Properties 

Access Property Values



Object Properties and Dot Notation



Graphing functions return the object or objects created by the function. For example:

 

h = plot(1:10); h refers to the line drawn in the graph of the values 1 through 10.



Dot notation is a new syntax to access object properties starting in R2014b. This syntax uses the object variable and the case-sensitive property name connected with a dot (.) to form an object dot property name notation:



object.PropertyName



If the object variable is nonscalar, use indexing to refer to a single object:



object(n).PropertyName



Scalar Object Variable



If h is the line created by the plot function, the expression h.Color is the value of this particular line's Color property:

    

h.Color ans =

 

c = h.Color; The variable c is a double.

 

whos Name

0 0.4470 0.7410 If you assign the color value to a variable:

Size

Bytes

Class

   

c 1x3 24 double h 1x1 112 matlab.graphics.chart.primitive.Line You can change the value of this line's Color property with an assignment statement:

 

h.Color = [0 0 1]; Use dot notation property references in expressions:

 

meanY = mean(h.YData); Or to change the property value:

 

h.LineWidth = h.LineWidth + 0.5; Reference other objects contained in properties with multiple dot references:

    

h.Annotation.LegendInformation.IconDisplayStyle ans =

  

ax = gca; ax.Title.FontWeight = 'normal'; Nonscalar Object Variable



Graphics functions can return an array of objects. For example:

      

y = rand(5); h = plot(y); size(h) ans =

 

h(1).LineStyle = '--'; Use the set function to set the LineStyle of all the lines in the array:

 

set(h,'LineStyle','--') Appending Data to Property Values



With dot notation, you can use "end" indexing to append data to properties that contain data arrays, such as line XDataand YData. For example, this code updates the line XData and YData together to grow the line. You must ensure the size of line's xand y-data are the same before rendering with the call to drawnow or returning to the MATLAB® prompt.

      

h = plot(1:10); for k = 1:5 h.XData(end + 1) = h.XData(end) + k; h.YData(end + 1) = h.YData(end) + k; drawnow end



The object variables returned by graphics functions are handles. Handles are references to the actual objects. Object variables that are handles behave in specific ways when copied and when the object is deleted.



Copy Object Variable



For example, create a graph with one line:

on Set the properties of objects contained in properties:

5 1 Access the line representing the first column in y using the array index:

Graphics Object Variables Are Handles

 

h = plot(1:10); Now copy the object variable to another variable and set a property value with the new object variable:

  

h2 = h; h2.Color = [1,0,0] Assigning the object variable h to h2 creates a copy of the handle, but not the object referred to by the variable. The value of the Color property accessed from variable h is the same as that accessed from variable h2.

    

h.Color ans =



Delete Object Variables



There are now two object variables in the workspace that refer to the same line.

  

whos Name Size Bytes Class h 1x1 112 matlab.graphics.chart.primitive.Line h2 1x1 112 matlab.graphics.chart.primitive.Line Now close the figure containing the line graph:

 

1 0 0 h and h2 refer to the same object. Copying a handle object variable does not copy the object.

 

close gcf The line object no longer exists, but the object variables that referred to the line do still exist:

  



whos Name Size Bytes Class h 1x1 112 matlab.graphics.chart.primitive.Line h2 1x1 112 matlab.graphics.chart.primitive.Line However, the object variables are no longer valid:

 

h.Color Invalid or deleted object.

 

h2.Color = 'blue' Invalid or deleted object.



To remove the invalid object variables, use clear:

 

clear h h2



To see what properties an object contains, use the get function:

 

get(h) MATLAB returns a list of the object properties and their current value:



    

Listing Object Properties

AlignVertexCenters: Annotation: BeingDeleted: BusyAction: ButtonDownFcn:

'off' [1x1 matlab.graphics.eventdata.Annotation] 'off' 'queue' ''

        

Children: [] Clipping: 'on' Color: [0 0.4470 0.7410] ... LineStyle: '-' LineWidth: 0.5000 Marker: 'none' ... You can see the values for properties with an enumerated set of possible values using the set function:

      

set(h,'LineStyle') '-' '--' ':' '-.' 'none' To display all settable properties including possible values for properties with an enumerated set of values, use set with the object variable:

 

set(h)



You can also access and modify properties using the set and get functions.



The basic syntax for setting the value of a property on an existing object is:



set(object,'PropertyName',NewPropertyValue)



To query the current value of a specific object property, use a statement of the form:



returned_value = get(object,'PropertyName');



Property names are always character vectors. You can use single quotes or a variable that is a character vector. Property values depend on the particular property.



Multi Object/Property Operations



If the object argument is an array, MATLAB sets the specified value on all identified objects. For example:

  

y = rand(5); h = plot(y); Set all the lines to red:

 

set(h,'Color','red') To set the same properties on a number of objects, specify property names and property values using a structure or cell array. For example, define a structure to set axes properties appropriately to display a particular graph:



view1.CameraViewAngleMode = 'manual';



view1.DataAspectRatio = [1 1 1];



view1.Projection = 'Perspective';



To set these values on the current axes, type:



set(gca,view1)



Query Multiple Properties



You can define a cell array of property names and use it to obtain the values for those properties. For example, suppose you want to query the values of the axes "camera mode" properties. First, define the cell array:

Modify Properties with set and get

  

camModes = {'CameraPositionMode','CameraTargetMode',... 'CameraUpVectorMode','CameraViewAngleMode'}; Use this cell array as an argument to obtain the current values of these properties:



get(gca,camModes)

 

ans =



Graphics Object Properties



View and set graphics object properties, define default values



You can control the behavior and appearance of a particular graphics object by setting its properties. To set properties, return the object as an output argument from the function that creates it. For example, the plot function returns a chart line object. Then, use dot notation to view and set properties. Dot notation works in R2014b and later. If you are using an earlier release, use the get and set functions instead. For more information, see Access Property Values.



p = plot(1:10,1:10);



p.LineWidth = 3;



Alternatively, you can set properties using name-value pair arguments when creating the object, such as plot(1:10,1:10,'LineWidth',3). Most plotting functions support name-value pair arguments.



Properties

        

Top-Level Objects Chart Objects Primitive Objects Function Objects Group Objects Illustration Objects Ruler Objects Annotation Objects

'auto' 'auto' 'auto' 'auto'

Functions

get

Query graphics object properties

set

Set graphics object properties

reset

Reset graphics object properties to their defaults

inspect

Open Property Inspector



Topics

 

Graphics Objects Graphics objects are the visual components used by MATLAB® to display data graphically.

 

Access Property Values You can set and query property values or return them to their original (factory default) values.



Features Controlled by Graphics Objects



Graphics objects represent data in intuitive and meaningful ways, such as line graphs, images, text, and combinations of these objects.

 

Automatically Calculated Properties When plotting functions create graphs, many of the axes properties that are under automatic control adjust to best display the graph.

 

Default Property Values Nearly all graphics object properties have predefined values, but you can define default property values.

 

Define Default Line Styles This example shows how to set default line styles.

 

Multilevel Default Values This example sets default values on more than one level in the hierarchy.

 

Default Values for Automatically Calculated Properties When you create a graph, MATLAB sets certain property values appropriately for the particular graph.

 

How MATLAB Finds Default Values All graphics object properties have values built into MATLAB. You can also define your own default values.

 

Factory-Defined Property Values Plotting functions use factory-defined property values if you do not specify values as arguments or as defaults.

 

DPI-Aware Behavior in MATLAB Learn about DPI-aware behavior that improves the appearance of graphical elements on high-resolution systems.

Call Functions These examples show how to call a MATLAB® function. To run the examples, you must first create numeric arrays A and B, such as: A = [1 3 5]; B = [10 6 4]; Enclose inputs to functions in parentheses: max(A) Separate multiple inputs with commas: max(A,B) Store output from a function by assigning it to a variable: maxA = max(A) Enclose multiple outputs in square brackets: [maxA, location] = max(A)

Call a function that does not require any inputs, and does not return any outputs, by typing only the function name: clc Enclose text inputs in single quotation marks: disp('hello world')

Related Examples 

Ignore Function Outputs

Ignore Function Outputs Open Script This example shows how to request specific outputs from a function. Request all three possible outputs from the fileparts function. helpFile = which('help'); [helpPath,name,ext] = fileparts(helpFile); The current workspace now contains three variables from fileparts: helpPath, name, and ext. In this case, the variables are small. However, some functions return results that use much more memory. If you do not need those variables, they waste space on your system. Request only the first output, ignoring the second and third. helpPath = fileparts(helpFile); For any function, you can request only the first outputs (where is less than or equal to the number of possible outputs) and ignore any remaining outputs. If you request more than one output, enclose the variable names in square brackets, []. Ignore the first output using a tilde (~). [~,name,ext] = fileparts(helpFile); You can ignore any number of function outputs, in any position in the argument list. Separate consecutive tildes with a comma, such as [~,~,ext] = fileparts(helpFile);

Continue Long Statements on Multiple Lines This example shows how to continue a statement to the next line using ellipsis (...). s = 1 - 1/2 + 1/3 - 1/4 + 1/5 ... - 1/6 + 1/7 - 1/8 + 1/9; Build a long character vector by concatenating shorter vectors together: mytext = ['Accelerating the pace of ' ... 'engineering and science']; The start and end quotation marks for a character vector must appear on the same line. For example, this code returns an error, because each line contains only one quotation mark:

mytext = 'Accelerating the pace of ... engineering and science' An ellipsis outside a quoted text is equivalent to a space. For example, x = [1.23... 4.56]; is the same as x = [1.23 4.56];

Create Shortcuts to Rerun Commands This example shows how to create, run, edit, and organize MATLAB® shortcuts. A MATLAB shortcut is an easy way to run a group of MATLAB language statements that you use regularly. For example, use a shortcut to set up your environment when you start working, or to set the same properties for figures you create. 1. On the Home tab, click New, and then select Command Shortcut. If the Shortcuts tab is on the desktop, you can also click New Shortcut in the Manage section. 2. Complete the Shortcut Editor dialog box: 1. In the Label field, enter a name for the shortcut. For this example, enter my_Shortcut. 2. In the Callback field, type statements you want the shortcut to run. You also can drag and drop statements from the Command Window, Command History Window, or a file. For this example, enter these statements: format compact clear workspace filebrowser clc

Tip If command prompts (>>) appear, MATLAB automatically removes them from the Callback field when you save the shortcut

3. In the Category field, type the name of a new category or select an existing category from the drop-down list. If you leave this field blank, the shortcut appears in the General section of the toolbar. 4. In the Icon field, select an icon. 5. Select both the Add to quick access toolbar and Show label on quick access toolbar options. 6. Click Save. The shortcut icon and label appear on the quick access toolbar. If the shortcut icon does not appear on the quick access toolbar, use the drop-down to see the full list. To organize and edit shortcuts, on the Shortcuts tab, in the Manage section, click Organize Shortcuts to open the Shortcuts Organizer dialog box. If the Shortcuts tab

is not visible, go to the Home tab, and in the Environment section, click Layout. Then, under Show, select Shortcuts Tab. 3. Run a shortcut by clicking its icon on the Shortcuts tab.

All the statements in the shortcut Callback field execute as if you ran those statements from the Command Window, although they do not appear in the Command History window.

Stop Execution To stop execution of a MATLAB® command, press Ctrl+C or Ctrl+Break. On Apple Macintosh platforms, you also can use Command+. (the Command key and the period key). Ctrl+C does not always stop execution for files that run a long time, or that call built-ins or MEXfiles that run a long time. If you experience this problem, include a drawnow, pause, or getframe function in your file, for example, within a large loop. Also, Ctrl+C might be less responsive if you start MATLAB with the -nodesktop option. Note: For certain operations, stopping the program might generate errors in the Command Window.

See Also drawnow | getframe | pause

drawnow Update figures and process callbacks collapse all in page

Syntax 

drawnow example



drawnow limitrate example



drawnow nocallbacks



drawnow limitrate nocallbacks



drawnow update



drawnow expose

Description example

drawnow updates figures and processes any pending callbacks. Use this command if you modify graphics objects and want to see the updates on the screen immediately. example

drawnow limitrate limits the number of updates to 20 frames per second. If it has been fewer than 50 milliseconds since the last update, or if the graphics renderer is busy with the previous change, then drawnow discards the new updates. Use this command if you are updating graphics objects in a loop and do not need to see every update on the screen. Skipping updates can create faster animations. Pending callbacks are processed, so you can interact with figures during animations. drawnow nocallbacks defers callbacks, such as mouse clicks, until the next full drawnow command. Use this option if you want to prevent callbacks from interrupting your code. For more information, see Actions Equivalent to drawnow. drawnow limitrate nocallbacks limits the number of updates to 20 frames per second, skips updates if the renderer is busy, and defers callbacks. drawnow update skips updates if the renderer is busy and defers callbacks. Note: This syntax is not recommended. Use the limitrate option instead.

drawnow expose updates figures, but defers callbacks. Note: This syntax is not recommended. Use the nocallbacks option instead.

Examples collapse all

Create Animation of Streaming Data

Open Script Create an animation of a line growing as it accumulates 2,000 data points. Use drawnow to display the changes on the screen after each iteration through the loop. h = animatedline; axis([0 4*pi -1 1]) x = linspace(0,4*pi,2000); for k = 1:length(x) y = sin(x(k)); addpoints(h,x(k),y); drawnow end

Skip Updates for Faster Animation

Open Script Create an animation of a line growing as it accumulates 10,000 points. Since there are 10,000 points, drawing each update on the screen is slow. Create a faster, smooth animation by limiting the number of updates using drawnow limitrate. Then, display the final updates on the screen by calling drawnow after the loop ends. h = animatedline; axis([0 4*pi -1 1]) x = linspace(0,4*pi,10000); for k = 1:length(x) y = sin(x(k)); addpoints(h,x(k),y); drawnow limitrate end drawnow

Precompute Data, Then Create Animation

Open Script Compute all the data before the animation loop. h = animatedline; axis([0 4*pi -1 1]) x = linspace(0,4*pi,10000); y = sin(x); for k = 1:length(x) addpoints(h,x(k),y(k)); drawnow limitrate end drawnow

If you have long computations, precomputing the data can improve perfomance. Precomputing minimizes the computation time by letting the computation run without interruptions. Additionally, it helps ensure a smooth animation by focusing on only graphics code in the animation loop.

More About collapse all

Actions Equivalent to drawnow These actions are equivalent to calling a full drawnow command: 

Returning to the MATLAB® prompt.



Using the figure, getframe, input, pause, and keyboard functions.



Using functions that wait for user input, such as waitforbuttonpress, waitfor, or ginput.

Tips 

The nocallbacks option always adds interrupting callbacks to the queue. If you want to discard interrupting callbacks, then use the Interruptible and BusyAction properties instead.

See Also pause | refreshdata | waitfor Introduced before R2006a

pause Stop MATLAB execution temporarily collapse all in page

Syntax 

pause



pause(n) example



pause(state) example



oldState = pause(state) example

Description pause temporarily stops MATLAB® execution and waits for the user to press any key. The pause function also temporarily stops the execution of Simulink ® models, but does not pause their repainting. Note: If you previously disabled the pause setting, reenable it using pause('on') for this call to take effect. example

pause(n) pauses execution for n seconds before continuing. Pausing must be enabled for this call to take effect. example

pause(state) enables, disables, or displays the current pause setting. example

oldState = pause(state) returns the current pause setting and sets the pause state as indicated by state. For example, if pausing is enabled, oldState = pause('off') returns 'on' in oldState and disables pausing.

Examples collapse all

Pause Execution

Open Script Pause execution for 5 seconds. MATLAB blocks, or hides, the command prompt (>>) while it pauses execution. n = 5; pause(n) Disable Pause Setting

Open Script Disable the pause setting and query the current state. pause('off') pause('query') ans = off Pause execution for 100 seconds. Since the pause setting is off, MATLAB ignores the request to pause execution, and immediately returns the command prompt. pause(100) Enable the pause setting. pause('on')

Save and Restore Pause State

Open Script Store the current pause setting and then disable the ability to pause execution. oldState = pause('off') oldState = on Query the current pause setting. pause('query') ans = off Restore the initial pause state. pause(oldState) pause('query') ans = on Alternatively, you can store the queried value of the pause state and then disable the ability to pause execution. oldState = pause('query'); pause('off') Restore the initial pause state. pause(oldState)

Input Arguments collapse all

n — Number of seconds nonnegative, real number Number of seconds to pause execution specified as a nonnegative, real number. Typing pause(inf) puts you into an infinite loop. To return to the MATLAB prompt, type Ctrl+C. Example: pause(3) pauses for 3 seconds. Example: pause(5/1000) pauses for 5 milliseconds. Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 state — Pause setting 'on' | 'off' | 'query' Pause control indicator specified as 'on', 'off', or 'query'. Use 'on' or 'off' to control whether the pausefunction is able to pause MATLAB execution. Use 'query' to query the current state of the pause setting. To run interactive code unattended, disable the pause setting.

More About collapse all

Tips 

The accuracy of the pause function is subject to the scheduling resolution of your operating system, and to other concurrent system activity. The accuracy is not guaranteed, and finer resolution results in higher relative error.



While MATLAB is paused, the following continue to execute:

o

Repainting of figure windows, Simulink block diagrams, and Java® windows

o

HG callbacks from figure windows

o

Event handling from Java windows

See Also drawnow | input | keyboard Introduced before R2006a

refreshdata Refresh data in graph when data source is specified collapse all in page

Syntax refreshdata refreshdata(figure_handle) refreshdata(object_handles) refreshdata(object_handles,'workspace')

Description refreshdata evaluates any data source properties (XDataSource, YDataSource, or ZDataSource) on all objects in graphs in the current figure. If the specified data source has changed, the MATLAB® software updates the graph to reflect this change. Note: The variable assigned to the data source property must be in the base workspace or you must specify the workspace option as 'caller'.

refreshdata(figure_handle) refreshes the data of the objects in the specified figure. refreshdata(object_handles) refreshes the data of the objects specified in object_handles or the children of those objects. Therefore, object_handles can contain figure, axes, or plot object handles. refreshdata(object_handles,'workspace') enables you to specify whether the data source properties are evaluated in the base workspace or the workspace of the function in which refreshdata was called. 'workspace' is can be one of these values: 

'base' — Evaluate the data source properties in the base workspace.



'caller' — Evaluate the data source properties in the workspace of the function that called refreshdata.

Examples collapse all

Refresh Graph with Updated Data

Open Script Plot a sine wave and return the chart line handle, h. x = linspace(0,8); y = sin(x);

figure h = plot(x,y);

Identify the data sources for the plot by setting the XDataSource and YDataSource properties of the line to x and y, respectively. Then, modify y. Call refreshdata so that the graph updates with the changes to y. h.XDataSource = 'x'; h.YDataSource = 'y'; y = sin(x.^3); refreshdata

More About collapse all

Tips The Linked Plots feature (see documentation for linkdata) sets up data sources for graphs and synchronizes them with the workspace variables they display. When you use this feature, you do not also need to call refreshdata, as it is essentially automatically triggered every time a data source changes. If you are not using the Linked Plots feature, you need to set the XDataSource, YDataSource, and/or ZDataSourceproperties of a graph in order to use refreshdata. You can do that programmatically or use the Property Editor, one of the plotting tools. In the Property Editor, select the graph (e.g., a chart line object) and type in (or select from the drop-down choices) the name(s) of the workspace variable(s) from which you want the plot to refresh, in the fields labelled X Data Source, Y Data Source, and/or Z Data Source. The call to refreshdata causes the graph to update.

See Also linkaxes | linkdata | linkprop Introduced before R2006a      



Trial Software Product Updates

Translate This Page

Documentation Home

MATLAB App Building GUIDE or Programmatic Workflow

  

Coding App Behavior MATLAB Functions



waitfor

    

ON THIS PAGE Syntax Description Examples See Also

waitfor Block execution and wait for condition

Syntax waitfor(h) waitfor(h,PropertyName) waitfor(h,PropertyName,PropertyValue)

Description waitfor(h) blocks the caller from executing statements until the MATLAB ® object identified by h closes (is deleted). When object h no longer exists, waitfor returns, enabling execution to resume. If the object does not exist, waitfor returns

immediately without processing any events. waitfor(h,PropertyName) blocks the caller from executing until the value of PropertyName (any property of the object h) changes or h closes (is deleted). If PropertyName is not a valid property for the object, MATLAB returns an error. waitfor(h,PropertyName,PropertyValue) blocks the caller from executing until the value of PropertyName for the object h changes to the specific value PropertyValue or h closes (is deleted). If the value of PropertyName is already PropertyValue, waitfor returns immediately without processing any events.

Here are some important characteristics of the waitfor function: 







The waitfor function prevents its caller from continuing, but callbacks that respond to various user actions (for example, pressing a mouse button) can still run. The waitfor function also blocks Simulink® models from executing, but callbacks do still execute. The waitfor function can block nested function calls. For example, a callback that executes while the waitforfunction is running can call waitfor. If a callback function of a UI component is currently executing the waitfor function, then that callback can be interrupted regardless of that component's Interruptible property value.



If you type Ctrl+C in the Command Window while the waitfor function is executing, the executing program terminates. To avoid terminating, the program can call the waitfor function within a try/catch block that handles the exception that typing Ctrl+C generates.

Examples Create a plot and pause execution of the rest of the statements until you close the figure window: f = warndlg('This is a warning.', 'A Warning Dialog'); disp('This prints immediately'); drawnow message

% Necessary to print the

waitfor(f); disp('This prints after you close the warning dialog');

Suspend execution until name of figure changes: f = figure('Name', datestr(now)); h = uicontrol('String','Change Name',... 'Position',[20 20 100 30],... 'Callback', 'set(gcbf, ''Name'', datestr(now))'); disp('This prints immediately'); drawnow message

% Necessary to print the

waitfor(f, 'Name'); disp('This prints after clicking the push button');

Display text object and wait for user to edit it: figure; textH = text(.5, .5, 'Edit me and click away'); set(textH,'Editing','on', 'BackgroundColor',[1 1 1]); disp('This prints immediately.'); drawnow waitfor(textH,'Editing','off'); set(textH,'BackgroundColor',[1 1 0]);

disp('This prints after text editing is complete.');

If you close the figure while waitfor is executing, an error occurs because the code attempts to access handles of objects that no longer exist. You can handle the error by enclosing code starting with the call to waitfor in a try/catch block, as follows: figure; textH = text(.5, .5, 'Edit me and click away'); set(textH,'Editing','on', 'BackgroundColor',[1 1 1]); disp('This prints immediately.'); drawnow % Use try/catch block to handle errors, % such as deleting figure try waitfor(textH,'Editing','off'); set(textH,'BackgroundColor',[1 1 0]); disp('This prints after text editing is complete.'); catch ME disp('This prints if figure is deleted:') disp(ME.message) % You can place other code to respond to the error here end

The ME variable is a MATLAB Exception object that you can use to determine the type of error that occurred. For more information, see Respond to an Exception.

See Also drawnow | keyboard | pause | uiresume | uiwait | waitforbuttonpress Introduced before R2006a

getframe Capture axes or figure as movie frame collapse all in page

Syntax 

F = getframe

example



F = getframe(ax) example



F = getframe(fig) example



F = getframe(___,rect)

Description example

F = getframe captures the current axes as it appears on the screen as a movie frame. F is a structure containing the image data. getframe captures the axes at the same size that it appears on the screen. It does not capture tick labels or other content outside the axes outline. example

F = getframe(ax) captures the axes identified by ax instead of the current axes. example

F = getframe(fig) captures the figure identified by fig. Specify a figure if you want to capture the entire interior of the figure window, including the axes title, labels, and tick marks. The captured movie frame does not include the figure menu and tool bars. F = getframe(___,rect) captures the area within the rectangle defined by rect. Specify rect as a four-element vector of the form [left bottom width height]. Use this option with either the ax or fig input arguments in the previous syntaxes.

Examples collapse all

Capture Contents of Current Axes Create a plot of random data. Capture the axes and return the image data. getframe captures the interior of the axes and the axes outline. It does not capture content that extends beyond the axes outline. plot(rand(5)) F = getframe;

F is a structure with the field cdata that contains the captured image data. Display the captured image data using imshow. figure imshow(F.cdata)

Capture Contents of Figure Create a surface plot. Capture the interior of the figure window, excluding the menu and tool bars. surf(peaks) F = getframe(gcf);

F is a structure with the field cdata that contains the captured image data. Display the captured image data using imshow. figure imshow(F.cdata)

Specify Rectangular Region to Capture Capture the interior of an axes plus a margin of 30 pixels in each direction. The added margin is necessary to include the tick labels in the capture frame. Depending on the size of the tick labels, the margin might need to be adjusted. Create a plot of random data. plot(rand(5))

Change the axes units to pixels and return the current axes position. The third and fourth elements of the position vector specify the axes width and height in pixels. drawnow ax = gca; ax.Units = 'pixels'; pos = ax.Position pos = 73.8000

47.2000

434.0000

342.3000

Create a four-element vector, rect, that defines a rectangular area covering the axes plus the desired margin. The first two elements of rect specify the lower left corner of the rectangle relative to the lower left corner of the axes. The last two elements of rect specify the width and height of the rectangle. Reset the axes units to the default value of 'normalized'. marg = 30; rect = [-marg, -marg, pos(3)+2*marg, pos(4)+2*marg]; F = getframe(gca,rect); ax.Units = 'normalized'; Display the captured image data using imshow. figure imshow(F.cdata)

Calculate Region to Include Title and Labels Calculate a margin around the axes so that the captured image data includes the title, axis labels, and tick labels. Create a plot with a title and an x-axis label. plot(rand(5)) xlabel('x values') title('Plot of Random Data')

Change the axes units to pixels and store the Position and TightInset property values for the axes. The TighInset property is a four-element vector of the form [left bottom right top]. The values are the margins used around the axes for the tick values and text labels. drawnow ax = gca; ax.Units = 'pixels'; pos = ax.Position; ti = ax.TightInset; Create a four-element vector, rect, that defines a rectangular area covering the axes plus the automatically calculated margin. The first two elements of rect specify the lower left corner of the rectangle relative to the lower left corner of the axes. The last two elements of rect specify the width and height of the rectangle. rect = [-ti(1), -ti(2), pos(3)+ti(1)+ti(3), pos(4)+ti(2)+ti(4)]; F = getframe(ax,rect); Display the captured image data using imshow. figure imshow(F.cdata)

Capture Specific Subplot Axes Create a figure with two subplots. In the upper subplot, plot a blue line. In the lower subplot, plot a red line. ax1 = subplot(2,1,1); plot(1:10,'b') ax2 = subplot(2,1,2); plot(1:10,'r')

Capture the contents of the lower subplot. getframe captures the interior and border of the subplot. It does not capture tick values or labels that extend beyond the outline of the subplot. F = getframe(ax2); Display the captured image data using imshow. figure imshow(F.cdata)

Record Frames and Play Movie Record frames of the peaks function vibrating by using getframe in a loop. Preallocate an array to store the movie frames. Z = peaks; surf(Z) axis tight manual ax = gca; ax.NextPlot = 'replaceChildren';

loops = 40; F(loops) = struct('cdata',[],'colormap',[]); for j = 1:loops X = sin(j*pi/10)*Z; surf(X,Z) drawnow F(j) = getframe(gcf); end Playback the movie two times. fig = figure; movie(fig,F,2)

Input Arguments collapse all

ax — Axes to capture axes object Axes to capture, specified as an axes object. Use this option if you want to capture an axes that is not the current axes. getframe captures the content within the smallest rectangle that encloses the axes outline. If you want to capture all the tick values and labels, then use the fig input argument instead. Example: F = getframe(ax); fig — Figure to capture figure object Figure to capture, specified as a figure object. Use gcf to capture the current figure. Example: F = getframe(gcf); rect — Rectangular area to capture four-element vector of the form [left bottom width height] Rectangular area to capture, specified as a four-element vector of the form [left bottom width height] in pixels. The left and bottom elements define the position of the lower left corner of the rectangle. The position is relative to the figure or axes that is specified as the first input argument to getframe. The width and height elements define the dimensions of the rectangle. Specify a rectangle that is fully contained within the figure window. Example: F = getframe(gcf,[0 0 560 420]);

Output Arguments collapse all

F — Movie frame structure Movie frame, returned as a structure with two fields:  





cdata — The image data stored as an array of uint8 values. The size of the image data array depends on your screen resolution. colormap — The colormap. On true color systems, this field is empty. Note: These are some important considerations about the size of cdata: If you query the size of the region that getframe captures (either the figure, the axes, or the region specified by rect), the size in pixels might not match the number of elements in cdata. This difference is because the number of elements in cdatadepends on your screen resolution (and operating system settings), but pixels in MATLAB® might not correspond to the actual pixels on your screen. Starting in R2015b, if you are using a high-resolution system, then the size of cdata might be larger than in previous releases or on other systems.

More About

collapse all

Pixels Distances in pixels are independent of your system resolution on Windows ® and Macintosh systems: 

On Windows systems, a pixel is 1/96th of an inch.



On Macintosh systems, a pixel is 1/72nd of an inch. On Linux® systems, the size of a pixel is determined by your system resolution.

Tips 

For the fastest performance when using getframe, make sure that the figure is visible on the screen. If the figure is not visible, getframe can still capture the figure, but performance can be slower.



For more control over the resolution of the image data, use the print function instead. The cdata output argument with print returns the image data. The resolution input argument controls the resolution of the image.

See Also frame2im | im2frame | image | imshow | movie | print Introduced before R2006a

Find Functions to Use This example shows how to find the name and description of a MathWorks ® function from the Command Window or Editor using the Function browser. The Function browser is not supported in live scripts. 1. Click the Browse for functions button, . In the Command Window, this button is to the left of the prompt. In the Editor, the button is on the Editor tab, in the Edit section. The Function browser opens.

Tip The Function browser closes when you move the pointer outside of it. To keep the browser open, drag it by the top edge to a different location.

2. Optionally, select a subset of products to display in the list. Click the product area at the bottom of the browser (where the text All installed products appears by default), and then set the Selected Products preference and click OK. This preference also applies to the Help browser. 3. Find functions by browsing the list or by typing a search term. For example, search for the term fourier.

In the search results, a parenthetical term after a function name indicates either that the function is in a product folder other than MATLAB®, or that there are multiple functions with the same name. For example, fft (comm) corresponds to the fft function in the Communications System Toolbox™ folder. 4. Select a function that you would like to use or learn more about, as follows. 

Insert the function name into the current window by double-clicking the name. Alternatively, drag and drop the function name into any tool or application.



View syntax information for the function by single-clicking its name. A brief description for each of the syntax options displays in a yellow pop-up window.

Tip The pop-up window automatically closes when you move your pointer to a new item in the results list. To keep the pop-up window open, drag it by the top edge to a different location.

You can change the font that the Function browser uses by setting preferences. On the Home tab, in the Environmentsection, select Preferences > Fonts. By default, the Function browser uses the desktop text font and the pop-up window uses the Profiler font.

To search for the specified text in other MATLAB desktop tools, change the selection in the Look in field. You can increase the amount of information available in the Command Window so that more text is available for searching. Doing so requires more memory. On the Home tab, in the Environment section, click Preferences. Select MATLAB >Command Window, and then increase the setting for Number of lines in the command window scroll buffer. Clearing the command window (for example, with the clc function), empties the scroll buffer. The cleared text is no longer available for searching. To clear your display in the Command Window without clearing the buffer, use the home function. Search Using Keyboard Shortcuts You can also perform an incremental search in the Command Window using keyboard shortcuts. 1. Begin an incremental search by using one of the defined keyboard shortcuts. Action

Windows® Default Shortcut

Macintosh or Emacs Default Shortcut

Initiate a forward incremental search.

Ctrl+Shift+S

Ctrl+S

Initiate a backward incremental search.

Ctrl+Shift+R

Ctrl+R

2. An incremental search field appears in the bottom right corner of the MATLAB Desktop window. For a forward search, the text F Inc Search appears. The F indicates a forward search. 3. Begin typing your search term. When you enter lowercase letters in the incremental search field, MATLAB looks for both lowercase and uppercase instances of the letters. For example, if you enter b, MATLAB looks for b and B. However, if you enter uppercase letters, MATLAB only looks for instances that match the case you entered. 4. Perform incremental search actions using these keyboard shortcuts: Action

Keyboard Shortcut

Complete a partially highlighted set of characters.

Ctrl+W

Find the next occurrence of a set of characters.

Ctrl+S

Remove characters from the incremental search field, back to the last successful search

Ctrl+G

5. If you search for a set of characters that does not appear in the Command Window text, Failing appears in the incremental search field. 6. End incremental searching by pressing Esc (escape), Enter, or any other key that is not a character or number. The incremental search field disappears. The cursor remains at the position where the text was last found, with the search text highlighted.

Find Text in the Command History Window You can search for text in the Command History Window. You can search for text either at the beginning of a command, or anywhere within a command. 1. In the Command History window, type in the Search field. To display the Search field if is not visible, click , and then select Find.

2. Begin typing your search term. The Command History window searches backward and selects the previous entry that contains the sequence of letters you typed.

3. Select from the different search options using the buttons to the right of the search field. Options include and

(match case),

(match anywhere within command),

(match at beginning of command).

4. Find the previous or next occurrence of the entry with the up and down arrow keys, respectively. 5. Press Esc to clear the search.

Check Syntax as You Type Syntax Highlighting To help you identify MATLAB® elements, some entries appear in different colors in the Command Window and the Editor. This is known as syntax highlighting. By default: 

Keywords are blue.



Character vectors are purple.



Unterminated character vectors are maroon.



Comments are green. if A > B 'greater' elseif A < B 'less' end Except for errors, output in the Command Window does not appear with syntax highlighting. When you paste or drag a selection from the Editor to another application, such as Microsoft® Word, the pasted text maintains the syntax highlighting colors and font characteristics from the Editor. MATLAB software pastes the selection to the Clipboard in RTF format, which many Microsoft Windows® and Macintosh applications support. You can change syntax highlighting preferences. On the Home tab, in the Environment section, click Preferences. Select MATLAB > Editor/Debugger > Languages. Preference changes do not apply in live scripts.

Delimiter Matching MATLAB indicates matched and mismatched delimiters, such as parentheses, brackets, and braces, to help you avoid syntax errors. MATLAB also indicates paired language keywords, such as for, if, while, else, and end statements. By default, MATLAB indicates matched and mismatched delimiters and paired language keywords as follows: 

Type a closing delimiter—MATLAB briefly highlights or underlines the corresponding opening delimiter.



Type more closing delimiters than opening delimiters—MATLAB puts a strike line through or underlines the unmatched delimiter.



Use the arrow keys to move the cursor over one delimiter—MATLAB briefly underlines both delimiters in a pair. If no corresponding delimiter exists, MATLAB puts a strike line through the unmatched delimiter. If a matching delimiter exists, but it is not visible on the screen, a pop-up window appears and shows the line containing the matching delimiter. Click in the pop-up window to go to that line.

The pop-up window for delimiter matching is not supported in live scripts. You can change delimiter matching indicators, and when and if they appear. On the Home tab, in the Environmentsection, click Preferences. Select MATLAB > Keyboard. Preference changes do not apply in live scripts.

Tab Completion MATLAB can help you avoid typographical errors by completing the names of functions, models, MATLAB objects, files, folders, variables, structures, graphics properties, parameters, and options. To complete names in the Command Window, type the first few characters of the name you want to complete, and then press the Tab key. If MATLAB presents a list of possible matches, use the arrow keys to select the name you want, and then press the Tab key.

In addition, you can: 

Clear the list without selecting anything, by pressing the Esc (escape) key.



Search a long list before making a selection, by adding additional characters to your original term.



Complete parts of a name that use dot notation by adding a dot, and then pressing the Tab key.



Complete the names and values of graphics properties. Begin typing the first part of a property, and then press the Tabkey. Type a comma after each property.



Complete parameter names and options for certain functions. When entering a command, at the location of a parameter or option, type ', and then press the Tab key. Completion of parameters and options is not available for all functions. For MATLAB to complete a file or folder name, it must be on the search path or in the current folder. Variables and properties must be in the current workspace. In the Editor, MATLAB completes:



Nested functions only when they are available at the current location of the cursor. Not supported in live scripts.



Names of variables defined in the active document. The variable must be valid at the current location of the cursor (that is, already defined).



Names of class properties and methods in class definition files. Not supported in live scripts. In the Editor, MATLAB does not complete field names of structure arrays defined only within the active file. Note: To add spaces within statements using the Tab key in the Editor, first add a space, and then press Tab. Otherwise, when tab completion is enabled, MATLAB attempts to complete a name.

Tab completion is enabled by default. To change this setting, on the Home tab, in the Environment section, click Preferences. Select MATLAB > Keyboard. Preference changes do not apply in live scripts. Example of Name Completion This example shows how to complete the name for the containers.Map.keys method. 1. In the Command Window, type help cont, and then press Tab. MATLAB displays a list of selections.

2. Select containers, and then press Tab. The Command Window displays help containers. 3. At the command prompt, add a dot after containers, and then press Tab. The Command Window displays: help containers.Map 4. At the command prompt, add a dot after Map, and then press Tab. MATLAB displays a new list.

5. Scroll down the list, select keys, and then press the Tab key. The Command Window displays help containers.Map.keys.

Function Syntax Hints As you enter a function in the Command Window or Editor, syntax hints open in a pop-up window to display allowable input arguments for a function. Function hints appear for both MATLAB installed functions and functions you create. The syntax hints for MATLAB functions comes from the documentation. The syntax for functions you create comes from the function definition statement (first executable line) in the MATLAB program file. That file must be on the search path or in the current folder. To use function syntax hints, type a function name with an opening parenthesis, and then pause. A tooltip opens showing the basic syntax for the function.

You can type a variable for any argument that appears in blue. Enter your variable names, and not the argument names shown in the window. The displayed syntax options change, based on the argument you just entered. Some function names are overloaded. That is, there are methods with the same name as a function that support different types of inputs. Overloaded methods require that you pass an object as the first input. When you specify the object name, the syntax hints update to reflect the associated method, as shown.

Function syntax hints are suggestions only. Some allowable arguments might not appear, or could be in black text when they should be blue. Function hints are enabled by default. To change this setting, on the Home tab, in the Environment section, click Preferences. Select MATLAB > Keyboard, and then set the options for Function hints. Preference changes do not apply in live scripts.

Write to a Diary File To keep an activity log of your MATLAB® session, use the diary function. diary creates a verbatim copy of your MATLAB session in a disk file (excluding graphics). For example, if you have the array A in your workspace, A = [ 1 2 3 4; 5 6 7 8 ]; execute these commands at the MATLAB prompt to export this array using diary: 1. Turn on the diary function. Optionally, you can name the output file diary creates: 2. diary my_data.out 3. Display the contents of the array you want to export. This example displays the array A. You could also display a cell array or other MATLAB class: 4. A = 5.

1

2

3

4

6.

5

6

7

8

7. Turn off the diary function: 8. diary off diary creates the file my_data.out and records all the commands executed in the MATLAB session until you turn it off: A =

1

2

3

4

5

6

7

8

diary off 9. Open the diary file my_data.out in a text editor and remove the extraneous text, if desired.

Related Documents

When You Start Matlab.docx
November 2019 17
When You Dont Study...
August 2019 27
When I Saw You...
June 2020 10
When You Come.docx
August 2019 31
When You Come.docx
August 2019 41