0% found this document useful (0 votes)
2 views48 pages

GET211 Lectures Introduction to MATLAB

This document outlines an introductory course on MATLAB, aimed at undergraduates with no formal prerequisites, focusing on basic programming concepts and MATLAB functionalities. It covers essential topics such as matrices, arrays, workspace variables, and basic programming techniques, with the goal of preparing students for further learning in MATLAB and other programming languages. The course includes grading based on attendance, homework, and a final exam, and utilizes MATLAB's help documentation as a reference.

Uploaded by

reteecent
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views48 pages

GET211 Lectures Introduction to MATLAB

This document outlines an introductory course on MATLAB, aimed at undergraduates with no formal prerequisites, focusing on basic programming concepts and MATLAB functionalities. It covers essential topics such as matrices, arrays, workspace variables, and basic programming techniques, with the goal of preparing students for further learning in MATLAB and other programming languages. The course includes grading based on attendance, homework, and a final exam, and utilizes MATLAB's help documentation as a reference.

Uploaded by

reteecent
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

MODULE 1- 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?

The owners (MathWorks) claim it is ‘The Language of Technical Computing’.


Millions of engineers and scientists worldwide use MATLAB® to analyze and design the
systems and products transforming our world. The matrix-based MATLAB language is the
world's most natural way to express computational mathematics.

Built-in graphics make it easy to visualize and gain insights from data.

The desktop environment invites experimentation, exploration, and discovery.

These MATLAB tools and capabilities are all rigorously tested and designed to work
together.

MATLAB helps you take your ideas beyond the desktop.

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.

Key Features of MATLAB


• High-level language for scientific and engineering computing
• Desktop environment tuned for iterative exploration, design, and problem-solving
• Graphics for visualizing data and tools for creating custom plots
• Apps for curve fitting, data classification, signal analysis, control system tuning, and many other tasks
• Add-on toolboxes for a wide range of engineering and scientific applications
• Tools for building applications with custom user interfaces
• Interfaces to C/C++, Java®, .NET, Python, SQL, Hadoop, and Microsoft® Excel®
• Royalty-free deployment options for sharing MATLAB programs with end users
MODULE 2- Getting Started with MATLAB
Topics
• 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

Topic 1- Desktop Basics


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 =

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.

If the command window is filled with commands one could type:

>> clc

To clear the command window or

>> home

To scroll the command window downwards to a clear section.


Topic 2- Matrices and Arrays
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 4

This type of array is a row 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 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

Matrix and Array Operations


MATLAB allows you to process all the values in a matrix using a single arithmetic operator or function.

a + 10
ans =

11 12 13
14 15 16
17 18 20

sin(a)
ans =

0.8415 0.9093 0.1411


-0.7568 -0.9589 -0.2794
0.6570 0.9894 -0.5440

To transpose a matrix, use a single quote ('):

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

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

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 4.0000 + 3.0000i


0.0000 - 1.0000i 0.0000 +10.0000i
Topic 3- Array Indexing
Open This Example

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

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

A 4x4 128 double


B 3x5x2 240 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

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.

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 strings with square brackets, just as you concatenate numeric arrays.

longText = [myText,' - ',otherText]


longText =

Hello, world - You're right

To convert numeric values to strings, 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
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.

To call a function, such as max, enclose its input arguments in parentheses:

A = [1 3 5];
max(A)
ans =

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 =

When there are multiple output arguments, enclose them in square brackets:

[maxA,location] = max(A)
maxA =

location =
3

Enclose any character string 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.

Common Errors When Calling Functions

Reference: MATLAB ® Programming Fundamentals R2019b, MathWorks page 1 -14 to 1-


18
The MathWorks, Inc.
1 Apple Hill Drive
Natick, MA 01760-2098
MATLAB Programming Fundamentals
© COPYRIGHT 1984–2019 by The MathWorks, Inc.
September 2019 Online only Revised for MATLAB 9.7 (Release 2019b)

Conflicting Function and Variable Names


MATLAB throws an error if a variable and function have been given the same name and
there is insufficient information available for MATLAB to resolve the conflict. You may see
an error message something like the following:
Error: <functionName> was previously used as a variable,
conflicting with its use here as the name of a function
or command.
where <functionName> is the name of the function.
Certain uses of the eval and load functions can also result in a similar conflict between
variable and function names.

Undefined Functions or Variables


You may encounter the following error message, or something similar, while working with
functions or variables in MATLAB:
Undefined function or variable 'x'.
These errors usually indicate that MATLAB cannot find a particular variable or MATLAB
program file in the current directory or on the search path. The root cause is likely to be
one of the following:
• The name of the function has been misspelled.
• The function name and name of the file containing the function are not the same.

• The toolbox to which the function belongs is not installed.


• The search path to the function has been changed.
• The function is part of a toolbox that you do not have a license for.
Follow the steps described in this section to resolve this situation.

Verify the Spelling of the Function Name


One of the most common errors is misspelling the function name. Especially with longer
function names or names containing similar characters (e.g., letter l and numeral one), it
is easy to make an error that is not easily detected.
If you misspell a MATLAB function, a suggested function name appears in the Command
Window. For example, this command fails because it includes an uppercase letter in the
function name:
accumArray
Undefined function or variable 'accumArray'.
Did you mean:
>> accumarray
Press Enter to execute the suggested command or Esc to dismiss it.
Make Sure the Function Name Matches the File Name
You establish the name for a function when you write its function definition line. This
name should always match the name of the file you save it to. For example, if you create a
function named curveplot,
function curveplot(xVal, yVal)
- program code -
then you should name the file containing that function curveplot.m. If you create a
pcode file for the function, then name that file curveplot.p. In the case of conflicting
function and file names, the file name overrides the name given to the function. In this
example, if you save the curveplot function to a file named curveplotfunction.m,
then attempts to invoke the function using the function name will fail:
curveplot
Undefined function or variable 'curveplot'.

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.

Topic 7- 2-D and 3-D Plots


Line Plots
Open This Example

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.

Plotting Implicit Functions (Xue & Chen, 2014)


If an explicit function y = f (t ) is given, we can generate a t vector first. Then we can use the dot
operation to compute, for each value in the t vector, the function value, to generate the vector y.
The function plot() can then be used to draw two-dimensional curves. However, if an implicit
function is given, such as x2 + 3y2 = 5, the above method cannot be used. The MATLAB function
ezplot() has to be used instead to draw implicit functions. Several examples are given here to
illustrate implicit function facilities.

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

set Set object properties.

set(H,'PropertyName',PropertyValue) sets the value of the specified

property for the graphics object with handle H. H can be a vector of

handles, in which case set sets the properties' values for all objects

of H.

set(H,a) where a is a structure whose field names are object property

names, sets the properties named in each field name with the values

contained in the structure.

set(H,pn,pv) sets the named properties specified in the cell array of

strings pn to the corresponding values in the cell array pv for all

objects specified in H. The cell array pn must be 1-by-N, but the cell

array pv can be M-by-N where M is equal to length(H) so that each

object will be updated with a different set of values for the list of

property names contained in pn.

set(H,'PropertyName1',PropertyValue1,'PropertyName2',PropertyValue2,...)

sets multiple property values with a single statement. Note that it

is permissible to use property/value string pairs, structures, and

property/value cell array pairs in the same call to set.

A = set(H, 'PropertyName')

set(H,'PropertyName')

returns or displays the possible values for the specified property of

the object with handle H. The returned array is a cell array of

possible value strings or an empty cell array if the property does not

have a finite set of possible string values.

A = set(H)
set(H)

returns or displays the names of the user-settable properties and

their possible values for the object with handle H. The return value

is a structure whose field names are the user-settable property names

of H, and whose values are cell arrays of possible property values or


empty cell arrays.

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.

% Generate random data from a uniform distribution


% and calculate the mean. Plot the data and the mean.

n = 50; % 50 data points


r = rand(n,1);
plot(r)

% 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, .

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.

nsamples = 5; % specifies number of samples to be taken


npoints = 50; % specifies the number of values within each sample

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.

nsamples = 5; % specifies number of samples to be taken


npoints = 50; % specifies the number of values within each sample
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

Iteration #4

sampleMean =
0.3988 0.4950 0.5365 0.4870

Iteration #5

sampleMean =

0.3988 0.4950 0.5365 0.4870 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

Solution

nsamples = 5; % specifies number of samples to be taken


npoints = 50; % specifies the number of values within each sample
for k = 1:nsamples
iterationString = ['Iteration #',int2str(k)];
disp(iterationString)
currentData = rand(npoints,1);
sampleMean(k) = mean(currentData)
end
overallMean = mean(sampleMean)

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

Note: ctrl c can be used to abort a conditional operation during execution.

Explain what each of the instructions in this script does:

[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

Topic 10- Entering Commands


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

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.

iskeyword str uses the MATLAB command format.

iskeyword returns a list of all MATLAB keywords.

Examples
To test if the word while is a MATLAB keyword,

iskeyword while

ans =

To obtain a list of all MATLAB keywords,

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

diary off suspends the diary.


diary on resumes diary mode using the current filename, or the default filename diary if none has yet been
specified.

diary filename is the unquoted form of the syntax.

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.

more(n) defines the length of a page to be n lines.

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.

Press the... To...

Return key Advance to the next line of output.

Space bar Advance to the next page of output.

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.

more is in the off state, by default.

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:

A = magic(5), B = ones(5) * 4.7; C = A./B


A =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9

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.

For example, select a portion of the following code:

Format Output in Command Window


Format Line Spacing in Output
By default, MATLAB® displays blanks lines in command 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 format option.

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

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.

Output Display Format Example Output

short (default) x = 1.3333 0.0000

short e x = 1.3333e+00 1.2345e-06

+ x = ++
Output Display Format Example Output

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

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:

On the Home tab, in the Environment section, click Preferences. Select MATLAB > Command Window.

Select Wrap Lines.

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:

In the Command Window, type more on to enable paged output.

Type the command that generates large output.

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.

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.
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);

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 string inputs in single quotation marks:

disp('hello world')

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 string by concatenating shorter strings together:

mystring = ['Accelerating the pace of ' ...

'engineering and science'];

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:

mystring = 'Accelerating the pace of ...

engineering and science'

An ellipsis outside a quoted string is equivalent to a space. For example,

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

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

How MATLAB Recognizes Command Syntax


Reference: MATLAB ® Programming Fundamentals R2019b, MathWorks page 1 -12
The MathWorks, Inc.
1 Apple Hill Drive
Natick, MA 01760-2098
MATLAB Programming Fundamentals
© COPYRIGHT 1984–2019 by The MathWorks, Inc.
September 2019 Online only Revised for MATLAB 9.7 (Release 2019b)
Consider the potentially ambiguous statement
ls ./d

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:

• Keywords are blue.


• Strings are purple.
• Unterminated strings 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 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.

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

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

Examples of valid names: Invalid names:

x6 6x

lastValue end

n_factorial n!

Conflicts with Function Names


Avoid creating variables with the same name as a function (such as i, j, mode, char, size, and path). In
general, variable names take precedence over function names. If you create a variable that uses the name of a
function, you sometimes get unexpected results.

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:

Case and Space Sensitivity


MATLAB® code is sensitive to casing, and insensitive to blank spaces except when defining arrays.

Uppercase and Lowercase

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 =

1.0000 0.0000 3.0000

You might also like