MATLAB
MATLAB
Like other well-known programming languages like Java, C#, etc., MATLAB has its own Integrated
Development Environment (IDE) and collection of libraries. Since it was initially known as the matrix
programming language, MATLAB is an acronym for "Matrix Laboratory." It is a programming language of the
fourth generation. It is a multi-paradigm, MATLAB. Therefore, it can be used with a variety of programming
paradigms, including functional, Visual, and Object-Oriented.
Cleve Moler, the department head of computer science at the University of New Mexico at the time, made the
initial discovery. He wanted to develop a different approach for his students to do linear algebra and numerical
computations without needing to utilize Fortran. Cleve Molar, Steve Bangart, and Jack Little founded
MathWorks in 1984 after seeing MATLAB's economic potential.
MATLAB Uses
The built-in functions of MATLAB offer top-notch resources for performing calculations, including
optimization, linear algebra, numerical solution of ordinary differential equations (ODEs), data analysis,
quadrate, signal processing, and many other scientific tasks.
Modern algorithms are used for the majority of these functions. There are many of these for both animations
and 2-D and 3-D graphics. MATLAB also supports an external interface.
The user can create their own functions in the MATLAB language. Thus they are not restricted to using only the
built-in functions.
Additional toolboxes are provided by MATLAB. These toolboxes were created for common uses such as neural
networks, symbolic computations, image processing, control system design, and statistics.
Developing algorithms
Performing linear algebra that is linear
Graph plotting for larger data sets
Data visualization and analysis
Numerical Matrix Computation
Advantages Of MATLAB
MATLAB Compiler
Ease of Use
Device-Independent Plotting
Platform Independence
Graphical User Interface
Predefined Functions
We will now look at each of the advantages more closely and in a detailed format to understand them better.
MATLAB Compiler
By converting MATLAB applications into a p-code that is machine independent and then, at runtime,
interpreting the p-code instruction, MATLAB is able to be flexible and independent of platforms. This approach
is comparable to that of Microsoft's Visual Basic programming language. Unfortunately, because the MATLAB
code, rather than being compiled, is interpreted, the resulting programs may run slowly.
There is a different MATLAB compiler available. With the help of this compiler, MATLAB programs can be
turned into genuine executables that execute more quickly than interpreted code. It is a terrific method to turn a
test MATLAB program into an executable that can be sold and provided to users.
Ease of Use
The program can be used to execute lengthy prewritten programs or as a scratchpad to evaluate command-line
inputted phrases. Applications can be created, modified, and debugged with the MATLAB debugger and built-
in integrated development environment. The language is ideal for quick prototyping of new apps because it is so
simple to use.
To make the software user-friendly, many program development tools are supported. They include a workspace
browser, an integrated editor/debugger, online documentation and manuals, and extensive demos.
Device-Independent Plotting
The imaging and basic plotting instructions in MATLAB are numerous. Any kind of graphical output device
offered by the machine running MATLAB can display the plots and images. This feature elevates MATLAB to
the level of a superior technical data visualization tool.
Platform Independence
Because MATLAB runs on a variety of computers, it offers a high degree of platform freedom. Linux, various
UNIX versions, Macintosh, Windows 2000/XP/Vista, and other operating systems all support the language.
Applications created on any platform will function fully on any other platform, and data files created for any
platform can ostensibly be read on any other platform. As a result, when the demands of the user change,
programs created in MATLAB can switch to new platforms.
A program's Graphical User Interface (GUI) can be created interactively by a programmer using a tool found in
MATLAB. With this capacity, a programmer can create sophisticated data-analysis algorithms that relatively
inexperienced people can utilize.
Predefined Functions
A sizable predefined functions library included with MATLAB offers tried-and-true answers to many common
technical problems. Assume, for instance, that we are creating software that must assess the statistics related to
a collection of input data. To perform computations like the median, standard deviation, arithmetic means, and
other calculations, we would typically need to develop our own subroutines or functions in the majority of
languages. Your job will be considerably more comfortable thanks to the hundreds of different services that are
already included in the MATLAB programming language.
Since we have explored the various advantages of MATLAB, we will now dive into the various disadvantages
of MATLAB.
Disadvantages of MATLAB
Cost
Interpreted language
Let us look at each of these in a little more detail.
Cost
Five to ten times as expensive as a typical FORTRAN compiler or C is a full copy of MATLAB. MATLAB is
cost-effective for organizations since this relatively high cost is more than offset by the shortened time an
engineer or scientist must spend developing functional software. However, the cost prevents most people from
even considering buying it. Fortunately, MATLAB also offers a low-cost Student Edition, which is a fantastic
resource for students who want to learn it. MATLAB's Student Edition and Full Edition are nearly identical.
Interpreted Language
The fact that it is an interpreted language and hence might run more slowly than a compiled language is its first
drawback. The MATLAB program can be correctly structured to check for this issue.
MATLAB Requirements
Each piece of computer software, including MATLAB, is run on an operating system. The operating system and
other parts are essential to a computer system's efficient operation.
Here, we provide all of the prerequisites for different types of operating systems that must be met before
downloading and installing MATLAB.
Mac 64-bit
Operating
RAM Disk space Graphics Processors
Systems
macOS
Mojave
(10.14) Minimum-any
No particular graphics x86-64 CPU
Minimum-3.3
card is necessary. from Intel or
GB of HDD
AMD
only for
Minimum-4 GB
macOS MATLAB
High
Sierra A hardwareaccelerated
(10.13) graphics card with 1GB Support for the
8GB Recommended of GPU memory and AVX2
SSD
OpenGL 3.3 instruction set
Recommende
compatibility is is advised and
d
advised. processor with
macOS 4 logical cores.
Sierra
(10.12)
Linux 64-bit
Operating
RAM Disk space Graphics Processors
Systems
Ubuntu
18.10
Ubuntu
18.04 LTS
Ubuntu
16.04 LTS
Ubuntu
14.04 LTS
Debian 9
SUSE
Linux
Enterprise
Desktop 15
SUSE
Linux
Enterprise
Server 12
(min. SP2)
SUSE Linux
Enterprise
Server 15
Windows 64-bit
Operating
RAM Disk space Graphics Processors
Systems
Windows
10
Hardware-
accelerated
graphics card with Support for the
1GB of GPU AVX2
Windows
Minimum 2.9 memory and instruction set is
7 Service
GB of HDD is support for advised, and a
Pack1
Minimum-4 GB required for OpenGL 3.3 is processor with 4
MATLAB advised. logical cores.
Windows
8 GB Recommended
Server
SSD No particular Minimum any
2019
Recommended graphics card is x86-64 CPU
necessary. from Intel or
AMD
Windows
Server
2016
MATLAB Downloading And Installation
Downloading MATLAB
Different MATLAB environments are available. For instance, it is offered separately for schools, start-ups,
enterprises, and individual use, and all of them are paid resources. Different flavors refer to different software
for different purposes. However, we may test it out for 30 days without paying a dime to MathWorks.
Step 1:
To download MATLAB, go to the official website at www.mathworks.com; you may be redirected to a website
in your country or another language, or you may be asked to click based on where you are located.
Step 2:
Click on the Trial Software link in the Try or Buy part of the web page's footer at the bottom.
Step 3:
After clicking on the link for the trial software, a new web page loads. In the box provided, type your email
address.
Step 4:
After selecting continue, you are prompted for more details to help MathWorks create your account and grant
you access to their products. Along with asking for the location and the email address you previously provided,
it also asks what you plan to use the MATLAB software for; choose either personal use or hobbyist use, and
then click Create.
Step 5:
Once more, a new page will open; select the option to continue using your current email to do so. Open the
email from MathWorks that has just arrived in your email inbox. Click the button labeled "Verify your email" to
do so now.
Step 6:
You need to fill out all the information about yourself, agree to the terms, then click the Create button on a new
webpage after being forwarded there.
Step 7:
Your confirmed email address will be displayed on the new page when it loads. Below it, there is an I agree on
the button; click it to confirm, then press the submit button. Now that we have registered with MathWorks.
Step 8:
Select one of the numerous types of possibilities for add-ons, and click on continue.
A choice will appear on the following page. Each of these is an option. You can proceed either by choosing one
of these alternatives or not.
Step 9:
Your email address and license number are displayed on a new page; make a note of this information.
It will first download the MATLAB installer, and the installer will then set up the MATLAB environment's
requirements. We'll use the Windows (64-bit) choice in this case, but you can choose your operating system
instead.
As a result, when we click on the Windows link, a pop-up window will appear on the screen. A binary
executable file will begin downloading after selecting the Save File option.
There will be an icon labeled "Downloading of MATLAB" in the folder where all of your downloaded files are
kept when you open the Downloads folder on your computer. This icon represents the binary executable file for
the installer.
After successfully downloading MATLAB, let us now look at how to install it.
MATLAB Installation
Step 1
Select the MATLAB icon twice. When the installer is asked to start in a pop-up after you click the icon, select
Run. On the screen, a MathWorks Installer window will appear.
Since the first choice, Log in with a MathWorks Account, is now selected by default, we'll use it.
Additionally, make sure the MATLAB environment is properly installed by checking your internet
connection. Therefore, select Next from the window's bottom menu.
Click the Next button once again after selecting yes to accept the licensing conditions on the following
screen.
When a new page loads, the first choice, Log in to your MathWorks Account, is automatically chosen. Enter
your email address and password from the MathWorks account creation process here. Click next while
keeping the image below in mind.
Step 2
A license ID that has already been chosen will be highlighted with a blue backdrop in the licensing selection
box that will open. Here, you must choose your license id—this is the id that was stored during STEP 9 of the
installer's download (we advised you to write it down at that time)—and then click Next once more.
There is no requirement for change in the folder location for the installation of MATLAB; simply click Next in
the newly appearing Folder Selection window.
Step 3
The Product Selection window is the next. Since MATLAB 9.6 is the MATLAB environment, it must be
selected. From the other products, you can select as many as you'd like before clicking Next.
The Installation Selections window will then appear; choose your preferred options there. You can always
click the Back button to return to the previous step whenever you feel like changing something.
The Confirmation window will appear after that. Here, all you need to do is confirm the items you'll be
downloading as part of the MATLAB installation and its add-on packages, along with their sizes, and then
click Install.
All of the products' downloads will begin after you click Install. Because the download is so large, you must
wait until it is finished.
Step 4
A message stating that the MATLAB needs to be activated displays once all items have been downloaded and
the installation is complete. Now, simply click the Next button.
A new window explaining the activation meaning opens after selecting Next. Press Next to continue.
Once more, a new window displaying your email address and the license ID for your items to open. Click the
Confirm button to continue.
Congratulations! You've successfully installed MATLAB and all of its related products after completing the
installation process. Click the Finish button now.
Step 5
In accordance with our selections made throughout the installation procedure, a shortcut for MATLAB will be
generated on the desktop. By selecting the MATLAB Downloading icon that has been placed on the desktop,
we can now work with MATLAB.
In accordance with our selections made throughout the installation procedure, a MATLAB shortcut will be
generated on the desktop. By selecting the MATLAB Downloading icon that has been placed on the desktop,
we can now work with MATLAB.
Command Window
The main window is this one. The MATLAB command prompt (>>) identifies it. You are presented with this
window by MATLAB when you start the function program. You enter all MATLAB instructions, including
those for running user-written programs, in this window. This window in MATLAB is a section of the program
that also includes other, smaller windows or panes.
Here is a picture of the screen you see when you first launch MATLAB:
Editor Window
Our programs are written, edited, created, and saved in these M-file files. Any text editor will work to complete
these tasks. The built-in editor of MATLAB is supported. But, we can use our editor by using the typical system
commands for editing files. The command is entered at the prompt for MATLAB from within MATLAB,
making sure to include the exclamation point (!). Exclamation characters cause MATLAB to temporarily
transfer control back to the operating system that is local, which then executes the commands necessary to
generate the character. After editing is finished, the control is transferred back to MATLAB.
Figure Window
The figure window or graphics, a distinct gray window with a (by default) white backdrop color, receives the
output of every graphics command we copied in the command window. If there is enough system memory, the
client can construct an unlimited number of figure windows.
MATLAB TUTORIAL
MATLAB – Overview.
MATLAB – Environment Setup.
MATLAB – Syntax.
MATLAB – Variables.
MATLAB – Commands.
MATLAB – M – Files.
MATLAB – Data Types.
MATLAB – Operator.
MATLAB – Decisions.
MATLAB – Loops.
MATLAB – Vectors.
MATLAB – Matrix.
MATLAB – Arrays.
MATLAB – Colon Notation.
MATLAB – Numbers.
MATLAB – Strings.
MATLAB – Functions.
MATLAB – Data Import.
MATLAB – Data Output.
MATLAB - Overview
It allows matrix manipulations; plotting of functions and data; implementation of algorithms; creation of user
interfaces; interfacing with programs written in other languages, including C, C++, Java, and FORTRAN;
analyze data; develop algorithms; and create models and applications.
It has numerous built-in commands and math functions that help you in mathematical calculations, generating
plots, and performing numerical methods.
MATLAB is used in every facet of computational mathematics. Following are some commonly used
mathematical calculations where it is used most commonly −
Features of MATLAB
Uses of MATLAB
MATLAB is widely used as a computational tool in science and engineering encompassing the fields of
physics, chemistry, math and all engineering streams. It is used in a range of applications including −
Setting up MATLAB environment is a matter of few clicks. The installer can be downloaded from here.
MathWorks provides the licensed product, a trial version and a student version as well. You need to log into the
site and wait a little for their approval.
After downloading the installer the software can be installed through few clicks.
Understanding the MATLAB Environment
MATLAB development IDE can be launched from the icon created on the desktop. The main working window
in MATLAB is called the desktop. When MATLAB is started, the desktop appears in its default layout −
The desktop has the following panels −
Current Folder − This panel allows you to access the project folders and files.
Command Window − This is the main area where commands can be entered at the command line. It is
indicated by the command prompt (>>).
Workspace − The workspace shows all the variables created and/or imported from files.
Command History − This panel shows or return commands that are entered at the command line.
If you are willing to use Octave on your machine ( Linux, BSD, OS X or Windows ), then kindly download
latest version from Download GNU Octave. You can check the given installation instructions for your machine.
MATLAB environment behaves like a super-complex calculator. You can enter commands at the >> command
prompt.
MATLAB is an interpreted environment. In other words, you give a command and MATLAB executes it right
away.
Hands on Practice
5+5
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is
−
ans = 10
Let us take up few more examples –
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is
–
ans = 9
Another example,
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is
–
ans = 1
Another example,
7/0 % Divide by zero
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is
−
ans = Inf
warning: division by zero
Another example,
732 * 20.3
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is
−
ans = 1.4860e+04
MATLAB provides some special expressions for some mathematical symbols, like pi for π, Inf for ∞, i (and j)
for √-1 etc. Nan stands for 'not a number'.
Use of Semicolon (;) in MATLAB
Semicolon (;) indicates end of statement. However, if you want to suppress and hide the MATLAB output for
an expression, add a semicolon after the expression.
For example,
x = 3;
y=x+5
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is
−
y= 8
Adding Comments
The percent symbol (%) is used for indicating a comment line. For example,
You can also write a block of comments using the block comment operators % { and % }.
The MATLAB editor includes tools and context menu items to help you add, remove, or change the format of
comments.
MATLAB supports the following commonly used operators and special characters −
Operator Purpose
\ Left-division operator.
/ Right-division operator.
. Decimal point.
= Assignment operator.
Special Variables and Constants
Name Meaning
Inf Infinity.
pi The number π
Naming Variables
Variable names consist of a letter followed by any number of letters, digits or underscore.
MATLAB is case-sensitive.
Variable names can be of any length, however, MATLAB uses only first N characters, where N is given by the
function namelengthmax.
The save command is used for saving all the variables in the workspace, as a file with .mat extension, in the
current directory.
For example,
save myfile
You can reload the file anytime later using the load command.
load myfile
MATLAB - Variables
MATLAB will execute the above statement and return the following result −
x=3
It creates a 1-by-1 matrix named x and stores the value 3 in its element. Let us check another example,
MATLAB will execute the above statement and return the following result −
x=4
Once a variable is entered into the system, you can refer to it later.
Variables must have values before they are used.
When an expression returns a result that is not assigned to any variable, the system assigns it to a
variable named ans, which can be used later.
For example,
sqrt(78)
MATLAB will execute the above statement and return the following result −
ans = 8.8318
sqrt(78);
9876/ans
MATLAB will execute the above statement and return the following result −
ans = 1118.2
MATLAB will execute the above statement and return the following result −
y = 441.84
Multiple Assignments
You can have multiple assignments on the same line. For example,
a = 2; b = 7; c = a * b
MATLAB will execute the above statement and return the following result −
c = 14
The who command displays all the variable names you have used.
who
MATLAB will execute the above statement and return the following result −
MATLAB will execute the above statement and return the following result −
Long assignments can be extended to another line by using an ellipses (...). For example,
initial_velocity = 0;
acceleration = 9.8;
time = 20;
final_velocity = initial_velocity + acceleration * time
MATLAB will execute the above statement and return the following result −
final_velocity = 196
The format Command
By default, MATLAB displays numbers with four decimal place values. This is known as short format.
However, if you want more precision, you need to use the format command.
For example −
format long
x = 7 + 10/3 + 5 ^ 1.2
MATLAB will execute the above statement and return the following result−
x = 17.2319816406394
Another example,
format short
x = 7 + 10/3 + 5 ^ 1.2
MATLAB will execute the above statement and return the following result −
x = 17.232
The format bank command rounds numbers to two decimal places. For example,
format bank
daily_wage = 177.45;
weekly_wage = daily_wage * 6
MATLAB will execute the above statement and return the following result −
weekly_wage = 1064.70
The format short e command allows displaying in exponential form with four decimal places plus the
exponent.
For example,
format short e
4.678 * 4.9
MATLAB will execute the above statement and return the following result −
ans = 2.2922e+01
The format long e command allows displaying in exponential form with four decimal places plus the exponent.
For example,
format long e
x = pi
MATLAB will execute the above statement and return the following result −
x = 3.141592653589793e+00
The format rat command gives the closest rational expression resulting from a calculation. For example,
format rat
4.678 * 4.9
MATLAB will execute the above statement and return the following result −
ans = 34177/1491
Creating Vectors
A vector is a one-dimensional array of numbers. MATLAB allows creating two types of vectors −
Row vectors
Column vectors
Row vectors are created by enclosing the set of elements in square brackets, using space or comma to delimit
the elements.
For example,
r = [7 8 9 10 11]
MATLAB will execute the above statement and return the following result −
r=
7 8 9 10 11
Another example,
r = [7 8 9 10 11];
t = [2, 3, 4, 5, 6];
res = r + t
MATLAB will execute the above statement and return the following result −
res =
9 11 13 15 17
Column vectors are created by enclosing the set of elements in square brackets, using semicolon(;) to delimit
the elements.
c=
7
8
9
10
11
Creating Matrices
In MATLAB, a matrix is created by entering each row as a sequence of space or comma separated elements,
and end of a row is demarcated by a semicolon. For example, let us create a 3-by-3 matrix as −
m = [1 2 3; 4 5 6; 7 8 9]
MATLAB will execute the above statement and return the following result −
m=
1 2 3
4 5 6
7 8 9
MATLAB - Commands
MATLAB is an interactive program for numerical computation and data visualization. You can enter a
command by typing it at the MATLAB prompt '>>' on the Command Window.
MATLAB provides various commands for managing a session. The following table provides all such
commands −
Command Purpose
MATLAB provides various useful commands for working with the system, like saving the current work in the
workspace as a file and loading the file later.
It also provides various commands for other system-related activities like, displaying date, listing files in the
directory, displaying current directory, etc.
Command Purpose
Command Purpose
The fscanf and fprintf commands behave like C scanf and printf functions. They support the following format
codes −
%s Format as a string.
%d Format as an integer.
The format function has the following forms used for numeric display −
The following table shows various commands used for working with arrays, matrices and vectors −
Command Purpose
Plotting Commands
MATLAB provides numerous commands for plotting graphs. The following table shows some of the commonly
used commands for plotting −
Command Purpose
MATLAB - M-Files
So far, we have used MATLAB environment as a calculator. However, MATLAB is also a powerful
programming language, as well as an interactive computational environment.
In previous chapters, you have learned how to enter commands from the MATLAB command prompt.
MATLAB also allows you to write series of commands into a file and execute the file as complete unit, like
writing a function and calling it.
The M Files
Scripts − script files are program files with .m extension. In these files, you write series of commands,
which you want to execute together. Scripts do not accept inputs and do not return any outputs. They
operate on data in the workspace.
Functions − functions files are also program files with .m extension. Functions can accept inputs and
return outputs. Internal variables are local to the function.
You can use the MATLAB editor or any other text editor to create your .mfiles. In this section, we will discuss
the script files. A script file contains multiple sequential lines of MATLAB commands and function calls. You
can run a script by typing its name at the command line.
To create scripts files, you need to use a text editor. You can open the MATLAB editor in two ways −
If you are using the command prompt, type edit in the command prompt. This will open the editor. You can
directly type edit and then the filename (with .m extension)
edit
Or
edit <filename>
The above command will create the file in default MATLAB directory. If you want to store all program files in
a specific folder, then you will have to provide the entire path.
Let us create a folder named progs. Type the following commands at the command prompt (>>) −
Alternatively, if you are using the IDE, choose NEW -> Script. This also opens the editor and creates a file
named Untitled. You can name and save the file after typing the code.
NoOfStudents = 6000;
TeachingStaff = 150;
NonTeachingStaff = 20;
After creating and saving the file, you can run it in two ways −
6170
Example
a = 5; b = 7;
c=a+b
d = c + sin(b)
e=5*d
f = exp(-d)
When the above code is compiled and executed, it produces the following result −
c= 12
d= 12.657
e= 63.285
f= 3.1852e-06
MATLAB does not require any type declaration or dimension statements. Whenever MATLAB encounters a
new variable name, it creates the variable and allocates appropriate memory space.
If the variable already exists, then MATLAB replaces the original content with new content and allocates new
storage space, where necessary.
For example,
Total = 42
The above statement creates a 1-by-1 matrix named 'Total' and stores the value 42 in it.
MATLAB provides 15 fundamental data types. Every data type stores data that is in the form of a matrix or
array. The size of this matrix or array is a minimum of 0-by-0 and this can grow up to a matrix or array of any
size.
The following table shows the most commonly used data types in MATLAB −
1 int8
8-bit signed integer
2 uint8
8-bit unsigned integer
3 int16
16-bit signed integer
4 uint16
16-bit unsigned integer
5 int32
32-bit signed integer
6 uint32
32-bit unsigned integer
7 int64
64-bit signed integer
8 uint64
64-bit unsigned integer
9 single
single precision numerical data
10 double
double precision numerical data
11 logical
logical values of 1 or 0, represent true and false respectively
12 char
character data (strings are stored as vector of characters)
cell array
13 array of indexed cells, each capable of storing an array of a different dimension
and data type
structure
14 C-like structures, each structure having named fields capable of storing an array
of a different dimension and data type
15 function handle
pointer to a function
16 user classes
objects constructed from a user-defined class
17 java classes
objects constructed from a Java class
Example
When the above code is compiled and executed, it produces the following result −
MATLAB provides various functions for converting, a value from one data type to another. The following table
shows the data type conversion functions −
Function Purpose
mat2cell Convert array to cell array with potentially different sized cells
Function Purpose
is Detect state
Example
x=3
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
x = 23.54
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
x = [1 2 3]
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
x = 'Hello'
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
x=3
ans = 0
ans = 1
ans = 1
ans = 1
ans = 1
x = 23.540
ans = 0
ans = 1
ans = 1
ans = 1
ans = 1
x=
1 2 3
ans = 0
ans = 1
ans = 1
ans = 0
x = Hello
ans = 0
ans = 0
ans = 1
ans = 0
ans = 0
MATLAB - Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.
MATLAB is designed to operate primarily on whole matrices and arrays. Therefore, operators in MATLAB
work both on scalar and non-scalar data. MATLAB allows the following types of elementary operations −
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operations
Set Operations
Arithmetic Operators
Matrix arithmetic operations are same as defined in linear algebra. Array operations are executed element by
element, both on one-dimensional and multidimensional array.
The matrix operators and array operators are differentiated by the period (.) symbol. However, as the addition
and subtraction operation is same for matrices and arrays, the operator is same for both cases. The following
table gives brief description of the operators −
Show Examples
+
1 Addition or unary plus. A+B adds the values stored in variables A and B. A and
B must have the same size, unless one is a scalar. A scalar can be added to a
matrix of any size.
-
2 Subtraction or unary minus. A-B subtracts the value of B from A. A and B must
have the same size, unless one is a scalar. A scalar can be subtracted from a
matrix of any size.
*
Matrix multiplication. C = A*B is the linear algebraic product of the matrices A
and B. More precisely,
3
For non-scalar A and B, the number of columns of A must be equal to the number
of rows of B. A scalar can multiply a matrix of any size.
.*
4 Array multiplication. A.*B is the element-by-element product of the arrays A and
B. A and B must have the same size, unless one of them is a scalar.
/
5 Slash or matrix right division. B/A is roughly the same as B*inv(A). More
precisely, B/A = (A'\B')'.
./
6
Array right division. A./B is the matrix with elements A(i,j)/B(i,j). A and B must
have the same size, unless one of them is a scalar.
\
Backslash or matrix left division. If A is a square matrix, A\B is roughly the same
7 as inv(A)*B, except it is computed in a different way. If A is an n-by-n matrix
and B is a column vector with n components, or a matrix with several such
columns, then X = A\B is the solution to the equation AX = B. A warning
message is displayed if A is badly scaled or nearly singular.
.\
8 Array left division. A.\B is the matrix with elements B(i,j)/A(i,j). A and B must
have the same size, unless one of them is a scalar.
9 ^
Matrix power. X^p is X to the power p, if p is a scalar. If p is an integer, the
power is computed by repeated squaring. If the integer is negative, X is inverted
first. For other values of p, the calculation involves eigenvalues and eigenvectors,
such that if [V,D] = eig(X), then X^p = V*D.^p/V.
.^
10 Array power. A.^B is the matrix with elements A(i,j) to the B(i,j) power. A and B
must have the same size, unless one of them is a scalar.
'
11 Matrix transpose. A' is the linear algebraic transpose of A. For complex matrices,
this is the complex conjugate transpose.
.'
12 Array transpose. A.' is the array transpose of A. For complex matrices, this does
not involve conjugation.
Relational Operators
Relational operators can also work on both scalar and non-scalar data. Relational operators for arrays perform
element-by-element comparisons between two arrays and return a logical array of the same size, with elements
set to logical 1 (true) where the relation is true and elements set to logical 0 (false) where it is not.
Show Examples
1 <
Less than
2 <=
Less than or equal to
3 >
Greater than
4 >=
Greater than or equal to
5 ==
Equal to
6 ~=
Not equal to
Logical Operators
Element-wise logical operators operate element-by-element on logical arrays. The symbols &, |, and ~ are the
logical array operators AND, OR, and NOT.
Short-circuit logical operators allow short-circuiting on logical operations. The symbols && and || are the
logical short-circuit operators AND and OR.
Show Examples
Bitwise Operations
Bitwise operators work on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows −
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; Now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
~A = 1100 0011
MATLAB provides various functions for bit-wise operations like 'bitwise and', 'bitwise or' and 'bitwise not'
operations, shift operation, etc.
Show Examples
Function Purpose
Set Operations
MATLAB provides various functions for set operations, like union, intersection and testing for set membership,
etc.
Show Examples
intersect(A,B)
1 Set intersection of two arrays; returns the values common to both A and B. The
values returned are in sorted order.
intersect(A,B,'rows')
2
Treats each row of A and each row of B as single entities and returns the rows
common to both A and B. The rows of the returned matrix are in sorted order.
ismember(A,B)
3 Returns an array the same size as A, containing 1 (true) where the elements of A
are found in B. Elsewhere, it returns 0 (false).
ismember(A,B,'rows')
4 Treats each row of A and each row of B as single entities and returns a vector
containing 1 (true) where the rows of matrix A are also rows of B. Elsewhere, it
returns 0 (false).
issorted(A)
5 Returns logical 1 (true) if the elements of A are in sorted order and logical 0
(false) otherwise. Input A can be a vector or an N-by-1 or 1-by-N cell array of
strings. A is considered to be sorted if A and the output of sort(A) are equal.
issorted(A, 'rows')
6 Returns logical 1 (true) if the rows of two-dimensional matrix A is in sorted
order, and logical 0 (false) otherwise. Matrix A is considered to be sorted if
A and the output of sortrows(A) are equal.
setdiff(A,B)
7 Sets difference of two arrays; returns the values in A that are not in B. The values
in the returned array are in sorted order.
setdiff(A,B,'rows')
8 Treats each row of A and each row of B as single entities and returns the rows
from A that are not in B. The rows of the returned matrix are in sorted order.
The 'rows' option does not support cell arrays.
9 setxor
Sets exclusive OR of two arrays
10 union
Sets union of two arrays
11 unique
Unique values in array
MATLAB - Decision Making
Decision making structures require that the programmer should specify one or more conditions to be evaluated
or tested by the program, along with a statement or statements to be executed if the condition is determined to
be true, and optionally, other statements to be executed if the condition is determined to be false.
Following is the general form of a typical decision making structure found in most of the programming
languages −
MATLAB provides following types of decision making statements. Click the following links to check their
detail −
if...else...end statement
2 An if statement can be followed by an optional else statement, which executes
when the boolean expression is false.
nested if statements
4
You can use one if or elseif statement inside another if or elseif statement(s).
switch statement
5 A switch statement allows a variable to be tested for equality against a list of
values.
nested switch statements
6
You can use one switch statement inside another switch statement(s).
There may be a situation when you need to execute a block of code several number of times. In general,
statements are executed sequentially. The first statement in a function is executed first, followed by the second,
and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and following is the
general form of a loop statement in most of the programming languages −
MATLAB provides following types of loops to handle looping requirements. Click the following links to check
their detail −
while loop
1
Repeats a statement or group of statements while a given condition is true. It tests
the condition before executing the loop body.
for loop
2
Executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
nested loops
3
You can use one or more loops inside any another loop.
Loop control statements change execution from its normal sequence. When execution leaves a scope, all
automatic objects that were created in that scope are destroyed.
MATLAB supports the following control statements. Click the following links to check their detail.
break statement
1
Terminates the loop statement and transfers execution to the statement
immediately following the loop.
continue statement
2
Causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.
MATLAB - Vectors
A vector is a one-dimensional array of numbers. MATLAB allows creating two types of vectors −
Row vectors
Column vectors
Row Vectors
Row vectors are created by enclosing the set of elements in square brackets, using space or comma to delimit
the elements.
r = [7 8 9 10 11]
MATLAB will execute the above statement and return the following result −
r=
7 8 9 10 11
Column Vectors
Column vectors are created by enclosing the set of elements in square brackets, using semicolon to delimit the
elements.
MATLAB will execute the above statement and return the following result −
c=
7
8
9
10
11
You can reference one or more of the elements of a vector in several ways. The i th component of a vector v is
referred as v(i). For example −
MATLAB will execute the above statement and return the following result −
ans = 3
When you reference a vector with a colon, such as v(:), all the components of the vector are listed.
MATLAB will execute the above statement and return the following result −
ans =
1
2
3
4
5
6
rv = [1 2 3 4 5 6 7 8 9];
sub_rv = rv(3:7)
MATLAB will execute the above statement and return the following result −
sub_rv =
3 4 5 6 7
Vector Operations
You can add or subtract two vectors. Both the operand vectors must be of same type and have same number of
elements.
Example
9 16 28 39 29
5 6 2 7 -11
Scalar Multiplication of Vectors
When you multiply a vector by a number, this is called the scalar multiplication. Scalar multiplication
produces a new vector of same type with each element of the original vector multiplied by the number.
Example
v = [ 12 34 10 8];
m=5*v
m=
60 170 50 40
Please note that you can perform all scalar operations on vectors. For example, you can add, subtract and divide
a vector with a scalar quantity.
Transpose of a Vector
The transpose operation changes a column vector into a row vector and vice versa. The transpose operation is
represented by a single quote (').
Example
r = [ 1 2 3 4 ];
tr = r';
v = [1;2;3;4];
tv = v';
disp(tr); disp(tv);
1
2
3
4
1 2 3 4
Appending Vectors
If you have two row vectors r1 and r2 with n and m number of elements, to create a row vector r of n plus m
elements, by appending these vectors, you write −
r = [r1,r2]
You can also create a matrix r by appending these two vectors, the vector r2, will be the second row of the
matrix −
r = [r1;r2]
However, to do this, both the vectors should have same number of elements.
Similarly, you can append two column vectors c1 and c2 with n and m number of elements. To create a column
vector c of n plus m elements, by appending these vectors, you write −
c = [c1; c2]
You can also create a matrix c by appending these two vectors; the vector c2 will be the second column of the
matrix −
c = [c1, c2]
However, to do this, both the vectors should have same number of elements.
Example
r1 = [ 1 2 3 4 ];
r2 = [5 6 7 8 ];
r = [r1,r2]
rMat = [r1;r2]
c1 = [ 1; 2; 3; 4 ];
c2 = [5; 6; 7; 8 ];
c = [c1; c2]
cMat = [c1,c2]
When you run the file, it displays the following result −
r=
Columns 1 through 7:
1 2 3 4 5 6 7
Column 8:
rMat =
1 2 3 4
5 6 7 8
c=
1
2
3
4
5
6
7
8
cMat =
1 5
2 6
3 7
4 8
Magnitude of a Vector
Magnitude of a vector v with elements v1, v2, v3, …, vn, is given by the equation −
You need to take the following steps to calculate the magnitude of a vector −
Take the product of the vector with itself, using array multiplication (.*). This produces a vector sv,
whose elements are squares of the elements of vector v.
sv = v.*v;
Use the sum function to get the sum of squares of elements of vector v. This is also called the dot
product of vector v.
dp= sum(sv);
Use the sqrt function to get the square root of the sum which is also the magnitude of the vector v.
mag = sqrt(s);
Example
v = [1: 2: 20];
sv = v.* v; %the vector with elements
% as square of v's elements
dp = sum(sv); % sum of squares -- the dot product
mag = sqrt(dp); % magnitude
disp('Magnitude:');
disp(mag);
Magnitude:
36.469
Dot product of two vectors a = (a1, a2, …, an) and b = (b1, b2, …, bn) is given by −
a.b = ∑(ai.bi)
Dot product of two vectors a and b is calculated using the dot function.
dot(a, b);
Example
v1 = [2 3 4];
v2 = [1 2 3];
dp = dot(v1, v2);
disp('Dot Product:');
disp(dp);
Dot Product:
20
Vectors with Uniformly Spaced Elements
To create a vector v with the first element f, last element l, and the difference between elements is any real
number n, we write −
v = [f : n : l]
Example
v = [1: 2: 20];
sqv = v.^2;
disp(v);
disp(sqv);
1 3 5 7 9 11 13 15 17 19
1 9 25 49 81 121 169 225 289 361
MATLAB - Matrix
In MATLAB, you create a matrix by entering elements in each row as comma or space delimited numbers and
using semicolons to mark the end of each row.
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8]
MATLAB will execute the above statement and return the following result −
a=
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
To reference an element in the mth row and nth column, of a matrix mx, we write −
mx(m, n);
For example, to refer to the element in the 2nd row and 5th column, of the matrix a, as created in the last section,
we type −
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
a(2,5)
MATLAB will execute the above statement and return the following result −
ans = 6
Let us create a column vector v, from the elements of the 4 th row of the matrix a −
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
v = a(:,4)
MATLAB will execute the above statement and return the following result −
v=
4
5
6
7
You can also select the elements in the mth through nth columns, for this we write −
a(:,m:n)
Let us create a smaller matrix taking the elements from the second and third columns −
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
a(:, 2:3)
MATLAB will execute the above statement and return the following result −
ans =
2 3
3 4
4 5
5 6
In the same way, you can create a sub-matrix taking a sub-part of a matrix.
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
a(:, 2:3)
MATLAB will execute the above statement and return the following result −
ans =
2 3
3 4
4 5
5 6
In the same way, you can create a sub-matrix taking a sub-part of a matrix.
3 4 5
4 5 6
To do this, write −
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
sa = a(2:3,2:4)
MATLAB will execute the above statement and return the following result −
sa =
3 4 5
4 5 6
You can delete an entire row or column of a matrix by assigning an empty set of square braces [] to that row or
column. Basically, [] denotes an empty array.
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
a( 4 , : ) = []
MATLAB will execute the above statement and return the following result −
a=
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
a(: , 5)=[]
MATLAB will execute the above statement and return the following result −
a=
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
Example
In this example, let us create a 3-by-3 matrix m, then we will copy the second and third rows of this matrix
twice to create a 4-by-3 matrix.
a = [ 1 2 3 ; 4 5 6; 7 8 9];
new_mat = a([2,3,2,3],:)
new_mat =
4 5 6
7 8 9
4 5 6
7 8 9
Matrix Operations
In this section, let us discuss the following basic and commonly used matrix operations −
You can add or subtract matrices. Both the operand matrices must have the same number of rows and columns.
Example
Create a script file with the following code −
a = [ 1 2 3 ; 4 5 6; 7 8 9];
b = [ 7 5 6 ; 2 0 8; 5 7 1];
c=a+b
d=a-b
c=
8 7 9
6 5 14
12 15 10
d=
-6 -3 -3
2 5 -2
2 1 8
Division of Matrices
You can divide two matrices using left (\) or right (/) division operators. Both the operand matrices must have
the same number of rows and columns.
Example
a = [ 1 2 3 ; 4 5 6; 7 8 9];
b = [ 7 5 6 ; 2 0 8; 5 7 1];
c=a/b
d=a\b
c=
d=
When you add, subtract, multiply or divide a matrix by a number, this is called the scalar operation.
Scalar operations produce a new matrix with same number of rows and columns with each element of the
original matrix added to, subtracted from, multiplied by or divided by the number.
Example
a = [ 10 12 23 ; 14 8 6; 27 8 9];
b = 2;
c=a+b
d=a-b
e=a*b
f=a/b
c=
12 14 25
16 10 8
29 10 11
d=
8 10 21
12 6 4
25 6 7
e=
20 24 46
28 16 12
54 16 18
f=
5.0000 6.0000 11.5000
7.0000 4.0000 3.0000
13.5000 4.0000 4.5000
Transpose of a Matrix
The transpose operation switches the rows and columns in a matrix. It is represented by a single quote(').
Example
a = [ 10 12 23 ; 14 8 6; 27 8 9]
b = a'
When you run the file, it displays the following result −
a=
10 12 23
14 8 6
27 8 9
b=
10 14 27
12 8 8
23 6 9
Concatenating Matrices
You can concatenate two matrices to create a larger matrix. The pair of square brackets '[]' is the concatenation
operator.
Horizontal concatenation
Vertical concatenation
When you concatenate two matrices by separating those using commas, they are just appended horizontally. It
is called horizontal concatenation.
Alternatively, if you concatenate two matrices by separating those using semicolons, they are appended
vertically. It is called vertical concatenation.
Example
a = [ 10 12 23 ; 14 8 6; 27 8 9]
b = [ 12 31 45 ; 8 0 -9; 45 2 11]
c = [a, b]
d = [a; b]
a=
10 12 23
14 8 6
27 8 9
b=
12 31 45
8 0 -9
45 2 11
c=
10 12 23 12 31 45
14 8 6 8 0 -9
27 8 9 45 2 11
d=
10 12 23
14 8 6
27 8 9
12 31 45
8 0 -9
45 2 11
Matrix Multiplication
Consider two matrices A and B. If A is an m x n matrix and B is an n x p matrix, they could be multiplied
together to produce an m x p matrix C. Matrix multiplication is possible only if the number of columns n in A is
equal to the number of rows n in B.
In matrix multiplication, the elements of the rows in the first matrix are multiplied with corresponding columns
in the second matrix.
Each element in the (i, j)th position, in the resulting matrix C, is the summation of the products of elements in
ith row of first matrix with the corresponding element in the jth column of the second matrix.
Example
a = [ 1 2 3; 2 3 4; 1 2 5]
b = [ 2 1 3 ; 5 0 -2; 2 3 -1]
prod = a * b
a=
1 2 3
2 3 4
1 2 5
b=
2 1 3
5 0 -2
2 3 -1
prod =
18 10 -4
27 14 -4
22 16 -6
Determinant of a Matrix
Determinant of a matrix is calculated using the det function of MATLAB. Determinant of a matrix A is given
by det(A).
Example
a = [ 1 2 3; 2 3 4; 1 2 5]
det(a)
a=
1 2 3
2 3 4
1 2 5
ans = -2
Inverse of a Matrix
The inverse of a matrix A is denoted by A−1 such that the following relationship holds −
AA−1 = A−1 A = 1
The inverse of a matrix does not always exist. If the determinant of the matrix is zero, then the inverse does not
exist and the matrix is singular.
Inverse of a matrix in MATLAB is calculated using the inv function. Inverse of a matrix A is given by inv(A).
Example
a = [ 1 2 3; 2 3 4; 1 2 5]
inv(a)
a=
1 2 3
2 3 4
1 2 5
ans =
-3.5000 2.0000 0.5000
3.0000 -1.0000 -1.0000
-0.5000 0 0.5000
MATLAB - Arrays
All variables of all data types in MATLAB are multidimensional arrays. A vector is a one-dimensional array
and a matrix is a two-dimensional array.
We have already discussed vectors and matrices. In this chapter, we will discuss multidimensional arrays.
However, before that, let us discuss some special types of arrays.
In this section, we will discuss some functions that create some special arrays. For all these functions, a single
argument creates a square array, double arguments create rectangular array.
For example −
zeros(5)
MATLAB will execute the above statement and return the following result −
ans =
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
For example −
ones(4,3)
MATLAB will execute the above statement and return the following result −
ans =
1 1 1
1 1 1
1 1 1
1 1 1
The eye() function creates an identity matrix.
For example −
eye(4)
MATLAB will execute the above statement and return the following result −
ans =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
The rand() function creates an array of uniformly distributed random numbers on (0,1) −
For example −
rand(3, 5)
MATLAB will execute the above statement and return the following result −
ans =
0.8147 0.9134 0.2785 0.9649 0.9572
0.9058 0.6324 0.5469 0.1576 0.4854
0.1270 0.0975 0.9575 0.9706 0.8003
A Magic Square
A magic square is a square that produces the same sum, when its elements are added row-wise, column-wise or
diagonally.
The magic() function creates a magic square array. It takes a singular argument that gives the size of the square.
The argument must be a scalar greater than or equal to 3.
magic(4)
MATLAB will execute the above statement and return the following result −
ans =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
Multidimensional Arrays
An array having more than two dimensions is called a multidimensional array in MATLAB. Multidimensional
arrays in MATLAB are an extension of the normal two-dimensional matrix.
Generally to generate a multidimensional array, we first create a two-dimensional array and extend it.
a = [7 9 5; 6 1 9; 4 3 2]
MATLAB will execute the above statement and return the following result −
a=
7 9 5
6 1 9
4 3 2
The array a is a 3-by-3 array; we can add a third dimension to a, by providing the values like −
a(:, :, 2)= [ 1 2 3; 4 5 6; 7 8 9]
MATLAB will execute the above statement and return the following result −
a=
ans(:,:,1) =
0 0 0
0 0 0
0 0 0
ans(:,:,2) =
1 2 3
4 5 6
7 8 9
We can also create multidimensional arrays using the ones(), zeros() or the rand() functions.
For example,
b = rand(4,3,2)
MATLAB will execute the above statement and return the following result −
b(:,:,1) =
0.0344 0.7952 0.6463
0.4387 0.1869 0.7094
0.3816 0.4898 0.7547
0.7655 0.4456 0.2760
b(:,:,2) =
0.6797 0.4984 0.2238
0.6551 0.9597 0.7513
0.1626 0.3404 0.2551
0.1190 0.5853 0.5060
We can also use the cat() function to build multidimensional arrays. It concatenates a list of arrays along a
specified dimension −
Where,
a = [9 8 7; 6 5 4; 3 2 1];
b = [1 2 3; 4 5 6; 7 8 9];
c = cat(3, a, b, [ 2 3 1; 4 7 8; 3 9 0])
c(:,:,1) =
9 8 7
6 5 4
3 2 1
c(:,:,2) =
1 2 3
4 5 6
7 8 9
c(:,:,3) =
2 3 1
4 7 8
3 9 0
Array Functions
MATLAB provides the following functions to sort, rotate, permute, reshape, or shift array contents.
Function Purpose
transpose Transpose
Examples
ans = 8
ans = 4
ans = 23
a=
1 2 3
4 5 6
7 8 9
b=
7 8 9
1 2 3
4 5 6
c=
8 9 7
2 3 1
5 6 4
Sorting Arrays
v=
23 45 12 9 5 0 19 17
ans =
0 5 9 12 17 19 23 45
m=
2 6 4
5 3 9
2 0 1
ans =
2 0 1
2 3 4
5 6 9
ans =
2 4 6
3 5 9
0 1 2
Cell Array
Cell arrays are arrays of indexed cells where each cell can store an array of a different dimensions and data
types.
The cell function is used for creating a cell array. Syntax for the cell function is −
C = cell(dim)
C = cell(dim1,...,dimN)
D = cell(obj)
Where,
C is the cell array;
dim is a scalar integer or vector of integers that specifies the dimensions of cell array C;
dim1, ... , dimN are scalar integers that specify the dimensions of C;
obj is One of the following −
o Java array or object
o .NET array of type System.String or System.Object
Example
c = cell(2, 5);
c = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 4 5}
When you run the file, it displays the following result −
c=
{
[1,1] = Red
[2,1] = 1
[1,2] = Blue
[2,2] = 2
[1,3] = Green
[2,3] = 3
[1,4] = Yellow
[2,4] = 4
[1,5] = White
[2,5] = 5
}
When you enclose the indices in first bracket, it refers to the set of cells.
For example −
MATLAB will execute the above statement and return the following result −
ans =
{
[1,1] = Red
[2,1] = 1
[1,2] = Blue
[2,2] = 2
}
You can also access the contents of cells by indexing with curly braces.
For example −
MATLAB will execute the above statement and return the following result −
ans = Blue
ans = Green
ans = Yellow
The colon(:) is one of the most useful operator in MATLAB. It is used to create vectors, subscript arrays,
and specify for iterations.
If you want to create a row vector, containing integers from 1 to 10, you write −
1:10
MATLAB executes the statement and returns a row vector containing the integers from 1 to 10 −
ans =
1 2 3 4 5 6 7 8 9 10
If you want to specify an increment value other than one, for example −
100: -5: 50
ans =
100 95 90 85 80 75 70 65 60 55 50
0:pi/8:pi
ans =
Columns 1 through 7
0 0.3927 0.7854 1.1781 1.5708 1.9635 2.3562
Columns 8 through 9
2.7489 3.1416
You can use the colon operator to create a vector of indices to select rows, columns or elements of arrays.
The following table describes its use for this purpose (let us have a matrix A) −
Format Purpose
A(:,:) is the equivalent two-dimensional array. For matrices this is the same as A.
Example
A = [1 2 3 4; 4 5 6 7; 7 8 9 10]
A(:,2) % second column of A
A(:,2:3) % second and third column of A
A(2:3,2:3) % second and third rows and second and third columns
A=
1 2 3 4
4 5 6 7
7 8 9 10
ans =
2
5
8
ans =
2 3
5 6
8 9
ans =
5 6
8 9
MATLAB - Numbers
MATLAB supports various numeric classes that include signed and unsigned integers and single-precision and
double-precision floating-point numbers. By default, MATLAB stores all numeric values as double-precision
floating point numbers.
You can choose to store any number or array of numbers as integers or as single-precision numbers.
All numeric types support basic array operations and mathematical operations.
MATLAB provides the following functions to convert to various numeric data types −
Function Purpose
Example
x=
x=
x=
38 23 45
x=
38 23 45
x=
38 23 45
x=
38 23 45
Example
Let us extend the previous example a little more. Create a script file and type the following code −
x=
38 23 45
x=
38 23 45
x=
{
[1,1] = 38
[1,2] = 23
[1,3] = 45
}
The functions intmax() and intmin() return the maximum and minimum values that can be represented with all
types of integer numbers.
Both the functions take the integer data type as the argument, for example, intmax(int8) or intmin(int64) and
return the maximum and minimum values that you can represent with the integer data type.
Example
The following example illustrates how to obtain the smallest and largest values of integers. Create a script file
and write the following code in it −
The functions realmax() and realmin() return the maximum and minimum values that can be represented with
floating point numbers.
Both the functions when called with the argument 'single', return the maximum and minimum values that you
can represent with the single-precision data type and when called with the argument 'double', return the
maximum and minimum values that you can represent with the double-precision data type.
Example
The following example illustrates how to obtain the smallest and largest floating point numbers. Create a script
file and write the following code in it −
% displaying the smallest and largest single-precision
% floating point number
str = 'The range for single is:\n\t%g to %g and\n\t %g to %g';
sprintf(str, -realmax('single'), -realmin('single'), ...
realmin('single'), realmax('single'))
MATLAB - Strings
Creating a character string is quite simple in MATLAB. In fact, we have used it many times. For example, you
type the following in the command prompt −
MATLAB will execute the above statement and return the following result −
MATLAB considers all variables as arrays, and strings are considered as character arrays. Let us use
the whos command to check the variable created above −
whos
MATLAB will execute the above statement and return the following result −
Interestingly, you can use numeric conversion functions like uint8 or uint16 to convert the characters in the
string to their numeric codes. The char function converts the integer vector back to characters −
Example
str_ascii =
84 117 116 111 114 105 97 108 39 115 32 80 111 105 110 116
84 117 116 111 114 105 97 108 39 115 32 80 111 105 110 116
The strings we have discussed so far are one-dimensional character arrays; however, we need to store more than
that. We need to store more dimensional textual data in our program. This is achieved by creating rectangular
character arrays.
Simplest way of creating a rectangular character array is by concatenating two or more one-dimensional
character arrays, either vertically or horizontally as required.
Using the MATLAB concatenation operator [] and separating each row with a semicolon (;). Please note
that in this method each row must contain the same number of characters. For strings with different
lengths, you should pad with space characters as needed.
Using the char function. If the strings are of different lengths, char pads the shorter strings with trailing
blanks so that each row has the same number of characters.
Example
doc_profile =
Zara Ali
Sr. Surgeon
R N Tagore Cardiology Research Center
doc_profile =
Zara Ali
Sr. Surgeon
RN Tagore Cardiology Research Center
Using the MATLAB concatenation operator, [] and separating the input strings with a comma or a
space. This method preserves any trailing spaces in the input arrays.
Using the string concatenation function, strcat. This method removes trailing spaces in the inputs.
Example
From our previous discussion, it is clear that combining strings with different lengths could be a pain as all
strings in the array has to be of the same length. We have used blank spaces at the end of strings to equalize
their length.
However, a more efficient way to combine the strings is to convert the resulting array into a cell array.
MATLAB cell array can hold different sizes and types of data in an array. Cell arrays provide a more flexible
way to store strings of varying length.
The cellstr function converts a character array into a cell array of strings.
Example
{
[1,1] = Zara Ali
[2,1] = Sr. Surgeon
[3,1] = R N Tagore Cardiology Research Center
}
MATLAB provides numerous string functions creating, combining, parsing, comparing and manipulating
strings.
Function Purpose
Functions for storing text in character arrays, combine character arrays, etc.
Examples
Formatting Strings
A = pi*1000*ones(1,5);
sprintf(' %f \n %.2f \n %+.2f \n %12.2f \n %012.2f \n', A)
ans = 3141.592654
3141.59
+3141.59
3141.59
000003141.59
Joining Strings
str1 = red-blue-green-yellow-orange
str2 = red,blue,green,yellow,orange
new_student =
{
[1,1] = Poulomi Dutta
}
first_names =
{
[1,1] = Zara
[1,2] = Neha
[1,3] = Monica
[1,4] = Madhu
[1,5] = Madhu
[1,6] = Bhawna
[1,7] = Nuha
[1,8] = Reva
[1,9] = Sunaina
[1,10] = Sofia
}
Comparing Strings
MATLAB - Functions
A function is a group of statements that together perform a task. In MATLAB, functions are defined in separate
files. The name of the file and of the function should be the same.
Functions operate on variables within their own workspace, which is also called the local workspace, separate
from the workspace you access at the MATLAB command prompt which is called the base workspace.
Functions can accept more than one input arguments and may return more than one output arguments.
The following function named mymax should be written in a file named mymax.m. It takes five numbers as
argument and returns the maximum of the numbers.
Create a function file, named mymax.m and type the following code in it −
The first line of a function starts with the keyword function. It gives the name of the function and order of
arguments. In our example, the mymax function has five input arguments and one output argument.
The comment lines that come right after the function statement provide the help text. These lines are printed
when you type −
help mymax
MATLAB will execute the above statement and return the following result −
MATLAB will execute the above statement and return the following result −
ans = 89
Anonymous Functions
An anonymous function is like an inline function in traditional programming languages, defined within a single
MATLAB statement. It consists of a single MATLAB expression and any number of input and output
arguments.
You can define an anonymous function right at the MATLAB command line or within a function or script.
This way you can create simple functions without having to create a file for them.
f = @(arglist)expression
Example
In this example, we will write an anonymous function named power, which will take two numbers as input and
return first number raised to the power of the second number.
result1 = 343
result2 = 7
result3 = 1.0000e-10
result4 = 9.5459
Any function other than an anonymous function must be defined within a file. Each function file contains a
required primary function that appears first and any number of optional sub-functions that comes after the
primary function and used by it.
Primary functions can be called from outside of the file that defines them, either from command line or from
other functions, but sub-functions cannot be called from command line or other functions, outside the function
file.
Sub-functions are visible only to the primary function and other sub-functions within the function file that
defines them.
Example
Let us write a function named quadratic that would calculate the roots of a quadratic equation. The function
would take three inputs, the quadratic co-efficient, the linear co-efficient and the constant term. It would return
the roots.
The function file quadratic.m will contain the primary function quadratic and the sub-function disc, which
calculates the discriminant.
quadratic(2,4,-4)
MATLAB will execute the above statement and return the following result −
ans = 0.7321
Nested Functions
You can define functions within the body of another function. These are called nested functions. A nested
function contains any or all of the components of any other function.
Nested functions are defined within the scope of another function and they share access to the containing
function's workspace.
Example
Let us rewrite the function quadratic, from previous example, however, this time the disc function will be a
nested function.
Create a function file quadratic2.m and type the following code in it −
disc;
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
end % end of function quadratic2
quadratic2(2,4,-4)
MATLAB will execute the above statement and return the following result −
ans = 0.73205
Private Functions
A private function is a primary function that is visible only to a limited group of other functions. If you do not
want to expose the implementation of a function(s), you can create them as private functions.
Example
Let us rewrite the quadratic function. This time, however, the disc function calculating the discriminant, will be
a private function.
Create a subfolder named private in working directory. Store the following function file disc.m in it −
Create a function quadratic3.m in your working directory and type the following code in it −
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
end % end of quadratic3
quadratic3(2,4,-4)
MATLAB will execute the above statement and return the following result −
ans = 0.73205
Global Variables
Global variables can be shared by more than one function. For this, you need to declare the variable as global in
all the functions.
If you want to access that variable from the base workspace, then declare the variable at the command line.
The global declaration must occur before the variable is actually used in a function. It is a good practice to use
capital letters for the names of global variables to distinguish them from other variables.
Example
Let us create a function file named average.m and type the following code in it −
global TOTAL;
TOTAL = 10;
n = [34, 45, 25, 45, 33, 19, 40, 34, 38, 42];
av = average(n)
When you run the file, it will display the following result −
av = 35.500
MATLAB - Data Import
Importing data in MATLAB means loading data from an external file. The importdata function allows loading
various data files of different formats. It has the following five forms −
1 A = importdata(filename)
Loads data into array A from the file denoted by filename.
2 A = importdata('-pastespecial')
Loads data from the system clipboard rather than from a file.
A = importdata(___, delimiterIn)
3 Interprets delimiterIn as the column separator in ASCII file, filename, or the
clipboard data. You can use delimiterIn with any of the input arguments in the
above syntaxes.
Example 1
Let us load and display an image file. Create a script file and type the following code in it −
filename = 'smile.jpg';
A = importdata(filename);
image(A);
When you run the file, MATLAB displays the image file. However, you must store it in the current directory.
Example 2
In this example, we import a text file and specify Delimiter and Column Header. Let us create a space-delimited
ASCII file with column headers, named weeklydata.txt.
filename = 'weeklydata.txt';
delimiterIn = ' ';
headerlinesIn = 1;
A = importdata(filename,delimiterIn,headerlinesIn);
% View data
for k = [1:7]
disp(A.colheaders{1, k})
disp(A.data(:, k))
disp(' ')
end
SunDay
95.0100
73.1100
60.6800
48.6000
89.1300
MonDay
76.2100
45.6500
41.8500
82.1400
44.4700
TuesDay
61.5400
79.1900
92.1800
73.8200
57.6300
WednesDay
40.5700
93.5500
91.6900
41.0300
89.3600
ThursDay
55.7900
75.2900
81.3200
0.9900
13.8900
FriDay
70.2800
69.8700
90.3800
67.2200
19.8800
SaturDay
81.5300
74.6800
74.5100
93.1800
46.6000
Example 3
Mathematics is simple
A = importdata('-pastespecial')
A=
'Mathematics is simple'
The importdata function is a high-level function. The low-level file I/O functions in MATLAB allow the most
control over reading or writing data to a file. However, these functions need more detailed information about
your file to work efficiently.
MATLAB provides the following functions for read and write operations at the byte or character level −
Function Description
MATLAB provides the following functions for low-level import of text data files −
Example
We have a text data file 'myfile.txt' saved in our working directory. The file stores rainfall data for three months;
June, July and August for the year 2012.
The data in myfile.txt contains repeated sets of time, month and rainfall measurements at five places. The
header data stores the number of months M; so we have M sets of measurements.
Rainfall Data
Months: June, July, August
M=3
12:00:00
June-2012
17.21 28.52 39.78 16.55 23.67
19.15 0.35 17.57 NaN 12.01
17.92 28.49 17.40 17.06 11.09
9.59 9.33 NaN 0.31 0.23
10.46 13.17 NaN 14.89 19.33
20.97 19.50 17.65 14.45 14.00
18.23 10.34 17.95 16.46 19.34
09:10:02
July-2012
12.76 16.94 14.38 11.86 16.89
20.46 23.17 NaN 24.89 19.33
30.97 49.50 47.65 24.45 34.00
18.23 30.34 27.95 16.46 19.34
30.46 33.17 NaN 34.89 29.33
30.97 49.50 47.65 24.45 34.00
28.67 30.34 27.95 36.46 29.34
15:03:40
August-2012
17.09 16.55 19.59 17.25 19.22
17.54 11.45 13.48 22.55 24.01
NaN 21.19 25.85 25.05 27.21
26.79 24.98 12.23 16.99 18.67
17.54 11.45 13.48 22.55 24.01
NaN 21.19 25.85 25.05 27.21
26.79 24.98 12.23 16.99 18.67
We will import data from this file and display this data. Take the following steps −
Open the file with fopen function and get the file identifier.
Describe the data in the file with format specifiers, such as '%s' for a string, '%d' for an integer, or '%f'
for a floating-point number.
To skip literal characters in the file, include them in the format description. To skip a data field, use an
asterisk ('*') in the specifier.
For example, to read the headers and return the single value for M, we write −
M = fscanf(fid, '%*s %*s\n%*s %*s %*s %*s\nM=%d\n\n', 1);
By default, fscanf reads data according to our format description until it does not find any match for the
data, or it reaches the end of the file. Here we will use for loop for reading 3 sets of data and each time,
it will read 7 rows and 5 columns.
We will create a structure named mydata in the workspace to store data read from the file. This structure
has three fields - time, month, and raindata array.
filename = '/data/myfile.txt';
rows = 7;
cols = 5;
12:00:00
June-2012
17.2100 17.5700 11.0900 13.1700 14.4500
28.5200 NaN 9.5900 NaN 14.0000
39.7800 12.0100 9.3300 14.8900 18.2300
16.5500 17.9200 NaN 19.3300 10.3400
23.6700 28.4900 0.3100 20.9700 17.9500
19.1500 17.4000 0.2300 19.5000 16.4600
0.3500 17.0600 10.4600 17.6500 19.3400
09:10:02
July-2012
12.7600 NaN 34.0000 33.1700 24.4500
16.9400 24.8900 18.2300 NaN 34.0000
14.3800 19.3300 30.3400 34.8900 28.6700
11.8600 30.9700 27.9500 29.3300 30.3400
16.8900 49.5000 16.4600 30.9700 27.9500
20.4600 47.6500 19.3400 49.5000 36.4600
23.1700 24.4500 30.4600 47.6500 29.3400
15:03:40
August-2012
17.0900 13.4800 27.2100 11.4500 25.0500
16.5500 22.5500 26.7900 13.4800 27.2100
19.5900 24.0100 24.9800 22.5500 26.7900
17.2500 NaN 12.2300 24.0100 24.9800
19.2200 21.1900 16.9900 NaN 12.2300
17.5400 25.8500 18.6700 21.1900 16.9900
11.4500 25.0500 17.5400 25.8500 18.6700
There are two ways to export a numeric array as a delimited ASCII data file −
where, my_data.out is the delimited ASCII data file created, num_array is a numeric array and −ascii is the
specifier.
where, my_data.out is the delimited ASCII data file created, num_array is a numeric array and dlm_char is the
delimiter character.
Example
The following example demonstrates the concept. Create a script file and type the following code −
num_array = [ 1 2 3 4 ; 4 5 6 7; 7 8 9 0];
save array_data1.out num_array -ascii;
type array_data1.out
dlmwrite('array_data2.out', num_array, ' ');
type array_data2.out
1234
4567
7890
Please note that the save -ascii command and the dlmwrite function does not work with cell arrays as input. To
create a delimited ASCII file from the contents of a cell array, you can
Either, convert the cell array to a matrix using the cell2mat function
Or export the cell array using low-level file I/O functions.
If you use the save function to write a character array to an ASCII file, it writes the ASCII equivalent of the
characters to the file.
h = 'hello';
save textdata.out h -ascii
type textdata.out
MATLAB executes the above statements and displays the following result. which is the characters of the string
'hello' in 8-digit ASCII format.
Diary files are activity logs of your MATLAB session. The diary function creates an exact copy of your session
in a disk file, excluding graphics.
diary
Optionally, you can give the name of the log file, say −
diary logdata.out
diary off
So far, we have exported numeric arrays. However, you may need to create other text files, including
combinations of numeric and character data, nonrectangular output files, or files with non-ASCII encoding
schemes. For these purposes, MATLAB provides the low-level fprintf function.
As in low-level I/O file activities, before exporting, you need to open or create a file with the fopen function
and get the file identifier. By default, fopen opens a file for read-only access. You should specify the permission
to write or append, such as 'w' or 'a'.
After processing the file, you need to close it with fclose(fid) function.
Example
% Table Header
fprintf(fid, 'Log Function\n\n');
Log Function
0.000000 -Inf
10.000000 2.302585
20.000000 2.995732
30.000000 3.401197
40.000000 3.688879
50.000000 3.912023
60.000000 4.094345
70.000000 4.248495
80.000000 4.382027
90.000000 4.499810
100.000000 4.605170