GET211 Lectures Introduction to MATLAB
GET211 Lectures Introduction to MATLAB
Prerequisites
There are no formal prerequisites for this course. It is intended to assist undergraduates in
learning the basics of programming in general and programming MATLAB® in particular.
Only the very basics of programming in MATLAB will be covered, with the goal of having
students become comfortable enough to continue learning MATLAB and other programming
languages on their own.
Access to MATLAB
Students need to have access to a computer with MATLAB installed. Which version matters
little as the course will be taught using very basic functionality which hardly changes
between versions.
Learning Outcomes
At the end of the course, students should be able to use MATLAB in their own work and be
prepared to deepen their MATLAB programming skills and tackle other languages for
computing, such as Java, C++, or Python.
The topics we will be treating to achieve this learning objectives are derived from the Help
functionality in MATLAB®. The topics are:
• Desktop Basics
• Matrices and Arrays
• Array Indexing
• Workspace Variables
• Character Strings
• Calling Functions
• 2-D and 3-D Plots
• Programming and Scripts
• Help and Documentation
Grading
Grades is based on attendance, homework, and a final exam.
References
MATLAB© help documentation
What is Programming?
A computer is a data processing machine that must be instructed on how to process a set of
data, to function. Many languages have been developed to instruct computers how to
process data.
Instructing a computer on how to perform is called programming.
In this course we will learn the basics of programming computers using the MATLAB®
language.
What is MATLAB?
Built-in graphics make it easy to visualize and gain insights from data.
These MATLAB tools and capabilities are all rigorously tested and designed to work
together.
You can run your analyses on larger data sets and scale up to clusters and clouds.
MATLAB code can be integrated with other languages, enabling you to deploy algorithms
and applications within web, enterprise, and production systems.
a = 1
MATLAB adds variable a to the workspace and displays the result in the Command Window.
a =
1
b = 2
b =
c = a + b
c =
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.
>> clc
>> home
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 4
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 2 3
4 5 6
7 8 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
a + 10
ans =
11 12 13
14 15 16
17 18 20
sin(a)
ans =
a'
ans =
1 4 7
2 5 8
3 6 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.0000
0 1.0000 0
0 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.000000000000000
0 1.000000000000000 0
0 0 0.999999999999998
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 4 9
16 25 36
49 64 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 8 27
64 125 216
343 512 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 2 3 1 2 3
4 5 6 4 5 6
7 8 10 7 8 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 2 3
4 5 6
7 8 10
1 2 3
4 5 6
7 8 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
Every variable in MATLAB® is an array that can hold many numbers. When you want to access selected
elements of an array, use indexing.
A = magic(4)
A =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 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)
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 2 3 13 0
5 11 10 8 0
9 7 6 12 0
4 14 15 1 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.
Topic 4- 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 Bytes Class Attributes
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.
load myfile.mat
You can also double-click a variable in the workspace, to view it in a spread-sheet like format. The
variable can then be modified in the spreadsheet in many ways. See the screenshot below:
Topic 5- Character Strings
Open This Example
A character string is a sequence of any number of characters enclosed in single quotes. You can assign a string
to a variable.
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
You can concatenate strings with square brackets, just as you concatenate numeric arrays.
f = 71;
c = (f-32)/1.8;
tempText = ['Temperature is ',num2str(c),'C']
tempText =
Temperature is 21.6667C
Topic 6- Calling Functions
Open This Example
MATLAB® provides a large number of functions that perform computational tasks. Functions are equivalent
to subroutines or methods in other programming languages.
A = [1 3 5];
max(A)
ans =
B = [10 6 4];
max(A,B)
ans =
10 6 5
maxA = max(A)
maxA =
When there are multiple output arguments, enclose them in square brackets:
[maxA,location] = max(A)
maxA =
location =
3
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.
If you encounter this problem, change either the function name or file name so that they
are the same. If you have difficulty locating the file that uses this function, use the
MATLAB Find Files utility as follows:
1
On the Home tab, in the File section, click Find Files.
2 Under Find files named: enter *.m
3 Under Find files containing text: enter the function name.
4 Click the Find button
Make Sure the Toolbox Is Installed
If you are unable to use a built-in function from MATLAB or its toolboxes, make sure that
the function is installed.
If you do not know which toolbox supports the function you need, search for the function
documentation at https://www.mathworks.com/help. The toolbox name appears at
the top of the function reference page.
Once you know which toolbox the function belongs to, use the ver function to see which
toolboxes are installed on the system from which you run MATLAB. The ver function
displays a list of all currently installed MathWorks® products. If you can locate the
toolbox you need in the output displayed by ver, then the toolbox is installed. For help
with installing MathWorks products, see the Installation Guide documentation.
If you do not see the toolbox and you believe that it is installed, then perhaps the MATLAB
path has been set incorrectly. Go on to the next section.
Verify the Path Used to Access the Function
This step resets the path to the default.
Because MATLAB stores the toolbox information in a cache file, you will need to first
update this cache and then reset the path. To do this,
1
On the Home tab, in the Environment section, click Preferences.
The Preference dialog box appears.
2 Under the MATLAB > General node, click the Update Toolbox Path Cache button.
3
On the Home tab, in the Environment section, click Set Path....
The Set Path dialog box opens.
4 Click Default.
A small dialog box opens warning that you will lose your current path settings if you
proceed. Click Yes if you decide to proceed.
(If you have added any custom paths to MATLAB, you will need to restore those later)
Run ver again to see if the toolbox is installed. If not, you may need to reinstall this
toolbox to use this function. For more information about installing a toolbox, see How do I
install additional toolboxes into an existing installation of MATLAB.
Once ver shows your toolbox, run the following command to see if you can find the
function:
which -all <functionname>
replacing <functionname> with the name of the function. You should be presented with
the path(s) of the function file. If you get a message indicating that the function name was
not found, you may need to reinstall that toolbox to make the function active.
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.
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.
Example The implicit function x2 + 3y2 = 5 can be drawn with the following statements,
and the ellipse obtained is shown in Fig. 2.7(a).
>> ezplot('x^2+3*y^2=5'), axis([-3,3,-2,2])
If a portion of the ellipse is expected, for instance the portion in the range x ∈ (−π/4, π),
y ∈ (−1, 3) is expected, the following statements can be given; the result obtained is shown in
Fig. 2.7(b).
>> figure; ezplot('x^2+3*y^2=5',[-pi/4,pi,-1,3]), axis([-3,3,-2,2])
Example For the more complicated implicit function
x2 sin (x + y2) + y2ex+y + 5 cos (x2 + y) = 0,
we can use the ezplot() function to draw its curves, as shown in the Figure It can be seen that
although the curves of the multi-valued implicit function look very complicated, it can still be drawn
directly with a single function call.
>> ezplot('x^2*sin(x+y^2)+y^2*exp(x+y)+5*cos(x^2+y)=0')
Example If the parametric equation for a spatial point (x, y) satisfies x = sin 3t cos t,
y = sin 3t sin t, t ∈ (0, π). The following MATLAB statements can be used, and the three-dimensional
trajectory can be obtained as shown in the Fig.
>> ezplot('sin(3∗t)∗cos(t)','sin(3∗t)∗sin(t)',[0,pi])
3-D Plots
Similar to two-dimensional plots, a function plot3() can be used to drawn three-dimensional
plots, with the syntax plot3(x, y, z, options), where x, y and z are vectors of the same length, storing the
coordinates, and the options available are exactly the same, as in 2-dimensional graphs (Xue & Chen, 2014):
Example:
For the time variable t, the spatial coordinates can be computed from x = sin t, y = cos t, z = t. Create a script
to show the trajectory in green:
% This scipt was created to illustrate the use of the plot3 function to
% plot 3 dimensional graphs
figure
t=-4*pi:0.1:4*pi; % this defines the values of the independent variable
U=sin(t); % This defines the values of the first dependent variable for the x-axis
V=cos(t); % This defines the values of the second dependent variable for the y-axis
W=t; % This defines the values of the third dependent variable for the z-axis
plot3(U,V,W,'g-'); axis square
grid on
OR
t=0: pi/50: 2∗pi; x=sin(t); y=cos(t); z=t; h=plot3(x,y,z,'g-');
set(h,'LineWidth',4∗get(h,'LineWidth'))
Alternatively the three-dimensional curve can be drawn with the following commands, and that
gives the new curve drawn in Fig. 2.10(b).
>> ezplot3('sin(t)','cos(t)','t',[0,2∗pi])
The set function
>> help set
handles, in which case set sets the properties' values for all objects
of H.
names, sets the properties named in each field name with the values
objects specified in H. The cell array pn must be 1-by-N, but the cell
object will be updated with a different set of values for the list of
set(H,'PropertyName1',PropertyValue1,'PropertyName2',PropertyValue2,...)
A = set(H, 'PropertyName')
set(H,'PropertyName')
possible value strings or an empty cell array if the property does not
A = set(H)
set(H)
their possible values for the object with handle H. The return value
Similar to the two-dimensional functions stem() and fill(), stem plots and filled plots can
be obtained respectively with stem3() and fill3()
Example:
% This scipt was created to illustrate the use of the plot3 function to
% plot 3 dimensional graphs
figure
t=-4*pi:0.1:4*pi; % this defines the values of the independent variable
U=sin(t); % This defines the values of the first dependent variable for the x-axis
V=cos(t); % This defines the values of the second dependent variable for the y-axis
W=t; % This defines the values of the third dependent variable for the z-axis
K=stem3(U,V,W,'g-'); axis square
set(K,'LineWidth',4*get(K,'LineWidth'),'MarkerSize',0.5*get(K,'MarkerSize'))
grid on
Example:
% This scipt was created to illustrate the use of the plot3 function to
% plot 3 dimensional graphs
figure
t=-4*pi:0.1:4*pi; % this defines the values of the independent variable
U=sin(t); % This defines the values of the first dependent variable for the x-axis
V=cos(t); % This defines the values of the second dependent variable for the y-axis
W=t; % This defines the values of the third dependent variable for the z-axis
K=fill3(U,V,W,'g-'); axis square
set(K,'LineWidth',4*get(K,'LineWidth'),'MarkerSize',0.5*get(K,'MarkerSize'))
grid on
Example
Ezplot3 can also be used to create 3-dimesional graphs as shown by entering the following command
in the command window:
ezplot3('cos(t)*sin(t)','cos(t)','t',[-4*pi,4*pi]), axis square
Surface Plots
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.
Example
Consider a two-dimensional function z = f (x, y) = (x2 − 2x)exp(−x2−y2−xy), and draw the three-dimensional
surface for the function.
[x,y]=meshgrid(-5:0.1:5);
>> z=(x.^2+2*x).*exp(-x.^2-y.^2-x.*y);
mesh(z)
>> axis square
>> figure
>> surf(z)
>> axis square
Similar results can be achieved using the functions ezmesh() and ezsurf().
>> ezmesh('(xˆ2-2∗x)∗exp(-xˆ2-yˆ2-x∗y)')
figure; ezsurf('(xˆ2-2∗x)∗exp(-xˆ2-yˆ2-x∗y)')
It should be noted that in the above functions, dot operation is not used, since x and y are simply
symbolic variables, not the mesh grid matrices.
Subplots
Open This Example
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/20:4*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');
To close the last figure window opened, type close
To close a specific figure window, type close followed by the name of the figure window
Topic 8- 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.
plotrand
You can also run scripts from the Editor by pressing the Run button, .
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. Browse for the folder, then Select the folder in the
Current Folder browser, right-click, and then select Add to Path.
Topic 9- 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 .
There is also a collection of easily understood examples demos on a wide variety of frequently
utilized feature of MATLAB. This collection can be accessed by typing the following at the command
prompt:
>> demo
To exit MATLAB and close all its windows, type >>exit or >>quit
MODULE 3- MATLAB Language
Fundamentals
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 (type: edit calcmean at the command prompt ) that
uses a for loop to calculate the mean of five random samples and the overall mean.
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.
calcmean
Iteration #1
sampleMean =
0.3988
Iteration #2
sampleMean =
0.3988 0.4950
Iteration #3
sampleMean =
Iteration #4
sampleMean =
0.3988 0.4950 0.5365 0.4870
Iteration #5
sampleMean =
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.
overallMean =
0.5178
Solution
[x,y]=meshgrid(-5*pi:pi/10:5*pi);
h=5;
for n=1:h
z=sin(n*x)+cos(n*y);
subplot(3,2,n)
surf(x,y,z)
end
Functions
iskeyword
Determine whether input is MATLAB keyword
Syntax
tf = iskeyword('str')
iskeyword str
iskeyword
Description
tf = iskeyword('str') returns logical 1 (true) if the string str is a keyword in the MATLAB® language
and logical 0 (false) otherwise. MATLAB keywords cannot be used as variable names.
Examples
To test if the word while is a MATLAB keyword,
iskeyword while
ans =
iskeyword
'break'
'case'
'catch'
'classdef'
'continue'
'else'
'elseif'
'end'
'for'
'function'
'global'
'if'
'otherwise'
'parfor'
'persistent'
'return'
'spmd'
'switch'
'try'
'while'
diary
Save Command Window text to file
collapse all in page
Syntax
diary
diary('filename')
diary off
diary on
diary filename
Description
The diary function creates a log of keyboard input and the resulting text output, with some exceptions
(see Tips for details). The output of diary is an ASCII file, suitable for searching in, printing, inclusion in most
reports and other documents. If you do not specify filename, the MATLAB® software creates a file
named diary in the current folder.
diary toggles diary mode on and off. To see the status of diary, type get(0,'Diary'). MATLAB returns
either onor off indicating the diary status.
diary('filename') writes a copy of all subsequent keyboard input and the resulting output (except it does
not include graphics) to the named file, where filename is the full pathname or filename is in the current
MATLAB folder. If the file already exists, output is appended to the end of the file. You cannot use
a filename called off oron. To see the name of the diary file, use get(0,'DiaryFile').
more
Control paged output for Command Window
Syntax
more on
more off
more(n)
A = more(state)
Description
more on enables paging of the output in the MATLAB® Command Window. MATLAB displays output one page
at a time. Use the keys defined in the table below to control paging.
more off disables paging of the output in the MATLAB Command Window.
A = more(state) returns in A the number of lines that are currently defined to be a page. The state input
can be one of the quoted strings 'on' or 'off', or the number of lines to set as the new page length.
By default, the length of a page is equal to the number of lines available for display in the MATLAB Command
Window. Manually changing the size of the command window adjusts the page length accordingly.
If you set the page length to a specific value, MATLAB uses that value for the page size, regardless of the size of
the command window. To have MATLAB return to matching page size to window size, type more off followed
by more on.
To see the status of more, type get(0,'More'). MATLAB returns either on or off, indicating the more status.
When you have enabled more and are examining output, you can do the following.
Q (for quit) Terminate display of the text. Do not use Ctrl+C to terminate more or you might
key generate error messages in the Command Window.
Example:
Type :
More on
help
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:
C =
3.6170 5.1064 0.2128 1.7021 3.1915
4.8936 1.0638 1.4894 2.9787 3.4043
0.8511 1.2766 2.7660 4.2553 4.6809
2.1277 2.5532 4.0426 4.4681 0.6383
2.3404 3.8298 5.3191 0.4255 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, right-click, and then
selectEvaluate 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.
x =
1.3333 0.0000
compact—Suppresses the display of blank lines
On the Home tab, in the Environment section, click Preferences. Select MATLAB > Command Window,
and then choose a Numeric format option.
format loose
format compact
Format Floating-Point Numbers
You can change the way numbers display in the Command Window. 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.
+ x = ++
Output Display Format Example Output
Note: The text display format affects only how numbers are shown, not how MATLAB computes or
saves them.
On the Home tab, in the Environment section, click Preferences. Select MATLAB > Command Window.
Click OK.
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:
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:
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.
Call Functions
These examples show how to call a MATLAB® function. To run the examples, you must first create numeric
arrays Aand B, such as:
A = rand(6).*magic(6);
B = rand(6).*magic(6);
max(A)
max(A,B)
maxA = max(A)
Call a function that does not require any inputs, and does not return any outputs, by typing only the function
name:
clc
disp('hello world')
The start and end quotation marks for a string must appear on the same line. For example, this code returns an
error, because each line contains only one quotation mark:
x = [1.23...
4.56];
is the same as
x = [1.23 4.56];
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 MEX-files 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
Win
the Command Window or Editor using the Function browser. The Function browser is not
supported in live scripts.
1. In the Command Window, right click anywhere and select Function Browser from the
list that appears.
In the Editor, the Browse for functions 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.
o 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.
o 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.
This could be a call to the ls function with the folder ./d as its argument. It also could
request element-wise division on the array ls, using the variable d as the divisor.
If you issue such a statement at the command line, MATLAB can access the current
workspace and path to determine whether ls and d are functions or variables. However,
some components, such as the Code Analyzer and the Editor/Debugger, operate without
reference to the path or workspace. In those cases, MATLAB uses syntactic rules to
determine whether an expression is a function call using command syntax.
In general, when MATLAB recognizes an identifier (which might name a function or a
variable), it analyzes the characters that follow the identifier to determine the type of
expression, as follows:
• An equal sign (=) implies assignment. For example:
ls =d
• An open parenthesis after an identifier implies a function call. For example:
ls('./d')
• Space after an identifier, but not after a potential operator, implies a function call
using command syntax. For example:
ls ./d
• Spaces on both sides of a potential operator, or no spaces on either side of the
operator, imply an operation on variables. For example, these statements are
equivalent:
ls ./ d
ls./d
Therefore, the potentially ambiguous statement ls ./d is a call to the ls function using
command syntax.
Topic 11- 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:
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 endstatements.
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 beeps. Beeping is not supported in live scripts.
• 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 Environment section, 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, Handle 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
theTab key.
• 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 Handle Graphics properties. Begin typing the first part of a property, and then
press the Tab key. Type a comma after each property.
• Complete parameter names and options for select 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.
• 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.
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.
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 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.
Valid Variable Names
A valid variable name starts with a letter, followed by letters, digits, or underscores. MATLAB® is case sensitive,
so Aand a are not the same variable. The maximum length of a variable name is the value that
the namelengthmaxcommand returns.
You cannot define variables with the same names as MATLAB keywords, such as if or end. For a complete list,
run the iskeyword command.
x6 6x
lastValue end
n_factorial n!
Check whether a proposed name is already in use with the exist or which function. exist returns 0 if there
are no existing variables, functions, or other artifacts with the proposed name. For example:
exist checkname
ans =
0
If you inadvertently create a variable with a name conflict, remove the variable from memory with
the clear function.
Another potential source of name conflicts occurs when you define a function that calls load or eval (or similar
functions) to add variables to the workspace. In some cases, load or eval add variables that have the same
names as functions. Unless these variables are in the function workspace before the call to load or eval, the
MATLAB parser interprets the variable names as function names. For more information, see:
In MATLAB code, use an exact match with regard to case for variables, files, and functions. For example, if you
have a variable, a, you cannot refer to that variable as A. It is a best practice to use lowercase only when naming
functions. This is especially useful when you use both Microsoft ® Windows® and UNIX®[1] platforms because their
file systems behave differently with regard to case.
When you use the help function, the help displays some function names in all uppercase, for example, PLOT,
solely to distinguish the function name from the rest of the text. Some functions for interfacing to
Oracle® Java® software do use mixed case and the command-line help and the documentation accurately reflect
that.
Spaces
Blank spaces around operators such as -, :, and ( ), are optional, but they can improve readability. For
example, MATLAB interprets the following statements the same way.
y = sin (3 * pi) / 2
y=sin(3*pi)/2
However, blank spaces act as delimiters in horizontal concatenation. When defining row vectors, you can use
spaces and commas interchangeably to separate elements:
A = [1, 0 2, 3 3]
A =
1 0 2 3 3
Because of this flexibility, check to ensure that MATLAB stores the correct values. For example, the statement [1
sin (pi) 3] produces a much different result than [1 sin(pi) 3] does.
[1 sin (pi) 3]
Error using sin
Not enough input arguments.
[1 sin(pi) 3]
ans =