0% found this document useful (0 votes)
139 views

MATLAB Applications

The document discusses MATLAB including what it is, its typical uses, features, construction, alternatives and advantages/disadvantages. MATLAB stands for matrix laboratory and was originally created for matrix operations. It is commonly used for math, modeling, data analysis and visualization. Some alternatives discussed are Scilab, Octave, FreeMat, Sage and R.

Uploaded by

madhuri nimse
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
139 views

MATLAB Applications

The document discusses MATLAB including what it is, its typical uses, features, construction, alternatives and advantages/disadvantages. MATLAB stands for matrix laboratory and was originally created for matrix operations. It is commonly used for math, modeling, data analysis and visualization. Some alternatives discussed are Scilab, Octave, FreeMat, Sage and R.

Uploaded by

madhuri nimse
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 252

Dilip S.

Aldar
K.B.P. College of Engineering & Polytechnic,
satara
What is MATLAB ?
 It stands for MATrix LABoratory
 MATLAB was invented in the late 1970s by Cleve Moler,
Originally a user interface for numerical linear algebra
routines .
 In 1984, Jack Little partnered with Moler and Steve
Bangert to rewrite MATLAB in C and founded the Math
Works Corporation that continues to support the product.
(www.mathworks.com)
MATLAB was originally written to provide easy access to
matrix software developed by the LINPACK and EISPACK
projects..

Cleve Moler Jack Little


2
What is MATLAB ?
•Typical uses include:
Math and computation
Algorithm development
Data acquisition
Modeling, simulation, and prototyping
Data analysis, exploration, and visualization
Scientific and engineering graphics
Application development, including graphical user
interface building
• It is a high-level programming language.
• It is also called as interpreted programming language.
D.S. Aldar K.B.P.C.O.E.P Satara 3
MATLAB Features
MATLAB

MATLAB
Programming
Language
User Defined Functions
Built In Functions
Graphics
Extra Functions

Extra Functions
Computations External Interface
•2 D Graphics •Linear Algebra (Mex-File)
•3 D Graphics •Data analysis • Interface with C, Fortran,
•Color & lighting •Polynomials & interpolations Java, LabView
•Animation

Toolboxes
•Signal Processing
•Statistics
•Control System
•Image processing
•Neural network
•Data Acquisition 4
And Many More
MATLAB Construction
• Core functionality: Compiled C-routines
• Most functionality is given as m-files, grouped into toolboxes
– m-files contain source code, can be copied and altered
– m-files are platform independent (PC, Unix/Linux, MAC)
•Simulation of dynamical systems is performed in Simulink

PDE Toolbox Statistics toolbox Coder

Signal Proc Financial Control Syst. Stateflow Blocksets

C-kernel Simulink
m-files
5
The MathWorks Product Suite

Stateflow Coder

Blocksets Simulink RTW

Toolboxes MATLAB Compiler 6


MATLAB and Toolboxes

D.S. Aldar K.B.P.C.O.E.P Satara 7


Application Deployment with MATLAB

D.S. Aldar K.B.P.C.O.E.P Satara 8


Application Deployment Workflow

D.S. Aldar K.B.P.C.O.E.P Satara 9


Key Industries

D.S. Aldar K.B.P.C.O.E.P Satara 10


Advantages & Disadvantages MATLAB
Advantages:
• Ease of Use
• Platform independent
• Predefined functions
• Graphical user interface
• Device Independent plotting
• MATLAB compiler
• FPGA & ASIC Design utilities
• Embedded Application development tools & Many more …..
Disadvantages:
• It is an interpreted language and therefore can execute
more slowly than compiled languages.
• Matlab is ten to fifteen times more expensive than
conventional C or Fortran compiler.
D.S. Aldar K.B.P.C.O.E.P Satara 11
Compiler vs. Interpreter

D.S. Aldar K.B.P.C.O.E.P Satara 12


ALTERNATIVES TO MATLAB

• Scilab is an open source scientific software package


for numerical computations providing a powerful
open computing environment for engineering and
scientific applications.
• Scilab includes hundreds of mathematical functions
with the possibility to add interactively programs
from various languages (C, C++, Fortran).
• It has sophisticated data structures (including lists,
polynomials, rational functions, linear systems), an
interpreter and a high level programming language.
D.S. Aldar K.B.P.C.O.E.P Satara 13
ALTERNATIVES TO MATLAB

• GNU Octave is a high-level language, primarily intended for


numerical computations. It provides a convenient command line
interface for solving linear and nonlinear problems numerically,
and for performing other numerical experiments using a
language that is mostly compatible with Matlab. It may also be
used as a batch-oriented language.
• Octave has extensive tools for solving common numerical linear
algebra problems, finding the roots of nonlinear equations,
integrating ordinary functions, manipulating polynomials, and
integrating ordinary differential and differential-algebraic
equations. It is easily extensible and customizable via user-
defined functions written in Octave’s own language, or using
dynamically loaded modules written in C++, C, Fortran, or other
languages. D.S. Aldar K.B.P.C.O.E.P Satara 14
ALTERNATIVES TO MATLAB

• FreeMat is a free environment for rapid engineering


and scientific prototyping and data processing. It is
similar to commercial systems such as MATLAB from
Mathworks, and IDL from Research Systems, but is
Open Source. FreeMat is available under the GPL
license.
• In addition to supporting many MATLAB functions
and some IDL functionality, it features codeless
interface to external C, C++, and Fortran code, further
parallel distributed algorithm development (via MPI),
and some extended volume and 3D visualization
capabilities.
D.S. Aldar K.B.P.C.O.E.P Satara 15
ALTERNATIVES TO MATLAB

• Sage is a free open-source mathematics software system licensed


under the GPL. It combines the power of many existing open-
source packages into a common Python-based interface. Sage’s
mission is to create a viable free open source alternative to
Magma, Maple, Mathematica and Matlab.
• Sage is free open source math software that supports research
and teaching in algebra, geometry, number theory, cryptography,
and related areas. Both the Sage development model and the
technology in Sage itself are distinguished by an extremely strong
emphasis on openness, community, cooperation, and
collaboration. Sage claims to be building the car rather than
reinventing the wheel.
• Sage can be used in several ways – notebook graphical interface,
interactive command line, programs and scripts.
D.S. Aldar K.B.P.C.O.E.P Satara 16
ALTERNATIVES TO MATLAB

• SciPy is an Open Source library of scientific tools for


Python. It depends on the NumPy library, and it
gathers a variety of high level science and engineering
modules together as a single package. SciPy provides
modules for statistics,optimization, numerical
integration,linear algebra, Fourier transforms, signal
processing,image processing, genetic algorithms, ODE
solvers, special functions, and more.
• SciPy is developed concurrently on both Linux and
Windows. It should also compile and run successfully
on Mac, Solaris, FreeBSD, and most other platforms
where Python is available.
D.S. Aldar K.B.P.C.O.E.P Satara 17
ALTERNATIVES TO MATLAB

• O-MATRIX is an easy-to-use integrated technical computing


environment and matrix-based scripting language.
• The high-performance integrated O-Matrix environment includes an
extensive collection of mathematical, statistical, engineering and
visualization functions with performance that far exceeds other
technical computing environments.
• The robust and diverse set of analysis functions enable the rapid
development of complex, computationally intensive scientific,
engineering, and technical computing solutions.
• Since 1992, Harmonic Software has been helping scientists,
engineers, and technical computing professionals in industries such
as aerospace, econometrics, electrical engineering, financial
modeling, and earth sciences obtain better results faster.
D.S. Aldar K.B.P.C.O.E.P Satara 18
ALTERNATIVES TO MATLAB

• R is a free software environment for statistical computing and


graphics.
• It is a GNU project which is similar to the S language and
environment which was developed at Bell Laboratories
(formerly AT&T, now Lucent Technologies) by John Chambers
and colleagues.
• R is available as Free Software under the terms of the Free
Software Foundation's GNU General Public License in source
code form. It compiles and runs on a wide variety of UNIX
platforms and similar systems (including FreeBSD and Linux),
Windows and MacOS.

D.S. Aldar K.B.P.C.O.E.P Satara 19


ALTERNATIVES TO MATLAB

• Numerics of any precision, symbolics, or visualization--Mathematica is


the ultimate computational tool, with system-wide technology to
ensure reliability, ease-of-use, and performance. Use Mathematica
computation directly, as the engine in an infrastructure, or integrated
into a standalone application.
– Simple calculations
– Plotting lists of points
– Plotting functions
– Combining two or more plots
– Fitting data to polynomials
– Generating and manipulating lists of numbers
– Complex numbers
– Derivatives and integrals
– Special functions
– Contour and surface plots
D.S. Aldar K.B.P.C.O.E.P Satara 20
ALTERNATIVES TO MATLAB
• Maple is a general-purpose commercial computer
algebra system.
• It was first developed in 1980 by the Symbolic
Computation Group at the University of Waterloo in
Waterloo, Ontario, Canada.
• Since 1988, it has been developed and sold commercially
by Waterloo Maple Inc. (also known as Maplesoft), a
Canadian company also based in Waterloo, Ontario.
• Users can enter mathematics in traditional mathematical
notation. Custom user interfaces can also be created.
• Maple incorporates a dynamically typed imperative-style
programming language which resembles Pascal
D.S. Aldar K.B.P.C.O.E.P Satara 21
The MATLAB Desktop Tools
• The command window
- type commands
• The Edit window
• The Graphic or Figure window
• The command history window
- view past commands
- save a whole session using diary
• The workspace Browser
- view program variables
- Clear to clear
- double click on a variable to see it in the Array Editor
• Current directory
• Launch pad
- access tools, demos and documentation
• Path
• Start D.S. Aldar K.B.P.C.O.E.P Satara 22
Managing the Workspace
>> who % displays list of variables
Your variables are:
Ap Ast Fc Fp Fs Fst M TW ans g

>> whos % displays list of variables with all details


Name Size Bytes Class

Ap 1x1 8 double array


Ast 1x1 8 double array
Fc 1x1 8 double array
Fp 1x1 8 double array Workspace can be opened by
Fs 1x1 8 double array typing workspace on command
Fst 1x1 8 double array prompt.
M 1x1 8 double array
TW 1x1 8 double array >> workspace
ans 1x1 2 int16 array
g 2x4 64 double array
23
D.S. Aldar K.B.P.C.O.E.P Satara
Grand total is 17 elements using 130 bytes
Managing the Workspace
CLEAR : removes all variables from the workspace.
CLEAR VARIABLES: does the same thing.
CLEAR GLOBAL: removes all global variables.
CLEAR FUNCTIONS: removes all compiled M- and MEX-functions.
CLEAR ALL: removes all variables, globals, functions and MEX links.
CLEAR ALL: at the command prompt also removes the Java packages import list.

CLC - Clear command window.


CLC clears the command window and homes the cursor.

pack - Consolidate workspace memory.


pack performs memory garbage collection. Extended MATLAB
sessions may use memory to become fragmented, preventing large
variables from being stored. pack is a command that saves all
variables on disk, clears the memory, and then reloads the variables.
D.S. Aldar K.B.P.C.O.E.P Satara 24
Managing the Workspace
save - Save workspace variables to disk.

save FILENAME - saves all workspace variables to the binary MAT-


file" named FILENAME.mat.
save FILENAME X - saves only X
save FILENAME -STRUCT S saves the fields of the scalar structure
S as individual variables within the file FILENAME.

D.S. Aldar K.B.P.C.O.E.P Satara 25


Managing the Workspace
ASCII Options:
save ... -ASCII uses 8-digit ASCII form instead of binary regardless
of file extension.
save ... -ASCII -DOUBLE uses 16-digit ASCII form.
save ... -ASCII -TABS delimits with tabs.
save ... -ASCII -DOUBLE -TABS 16-digit, tab delimited.

MAT Options:
save ... -MAT saves in MAT format regardless of extension.
save ... -V6 saves a MAT-file that MATLAB 6 can LOAD.
save ... -V4 saves a MAT-file that MATLAB 4 can LOAD.
save ... -APPEND adds the variables to an existing file (MAT-file
only).
D.S. Aldar K.B.P.C.O.E.P Satara 26
Managing the Workspace
saveas - Save Figure or model to desired output format.
saveas(H,'FILENAME')
Will save the Figure or model with handle H to file called FILENAME.
The format of the file is determined from the extension of FILENAME.
saveas(H,'FILENAME','FORMAT')
Will save the Figure or model with handle H to file called FILENAME.
in the format specified by FORMAT. FORMAT can be the same values as
extensions of FILENAME. The FILENAME extension does not have to be
the same as FORMAT. Given FORMAT overrides FILENAME extension.

Valid options for FORMAT are:


'fig' - save figure to a single binary FIG-file. Reload using OPEN.
'm' - save figure to binary FIG-file, and produce callable M-file for reload.
'mfig' - same as M.
'mmat' - save figure to callable M-file as series of creation commands
with param-value pair arguments. L
D.S. Aldar K.B.P.C.O.E.P Satara 27
Managing the Workspace
LOAD Load workspace variables from disk.
LOAD FILENAME - retrieves all variables from a file given a full
pathname or a MATLABPATH relative partial pathname (see
PARTIALPATH). If FILENAME has no extension LOAD looks for
FILENAME.mat and treats it as a binary "MAT-file". If FILENAME
has an extension other than .mat, it is treated as ASCII.

Example:
>> load mtlb;
>> wavplay(mtlb,Fs);
>>save matlab;
>> wavemenu
… and import file to wavemenu

D.S. Aldar K.B.P.C.O.E.P Satara 28


Managing the Workspace
memory - Help for memory limitations.
If the OUT OF memory error message is encountered, there is no more room in
memory for new variables. You must free up some space before you may
proceed. One way to free up space is to delete some variables (see CLEAR).
Another is to issue the command PACK (See PACK). PACK compresses the detain
memory, opening up larger contiguous blocks.
recycle - Set option to move deleted files to recycle folder.
The purpose of the recycle function is to help the DELETE function determine
whether the deleted files should be moved to the recycle bin on the PC and
Macintosh, moved to a temporary folder on Unix, or deleted.
Example: Start from a state where file recycling has been turned off. Check the
current recycle state:
>> recycle
ans = off
Turn file recycling on. Delete a file and verify that it has been transferred to the
recycle bin or temporary folder:
>> recycle on; >> delete myfile.txt 29
Managing commands and functions
what - List MATLAB-specific files in directory.
w = what Returns the results of what in a structure array with the fields:
path -- path to directory
m -- cell array of m-file names.
mat -- cell array of mat-file names.
mex -- cell array of mex-file names.
mdl -- cell array of mdl-file names.
p -- cell array of p-file names.
classes -- cell array of class names.
>> what

which Locate functions and files.


which FUN displays the full pathname of the function with the name FUN.
>> which('try1.m')
C:\Documents and Settings\admin\My Documents\MATLAB\try1.m

D.S. Aldar K.B.P.C.O.E.P Satara 30


Managing commands and functions
type - List M-file or contents of file.
type foo.bar - lists the ascii file called 'foo.bar'.
type foo - lists the ascii file called 'foo.m'.

Example:
>> type sinetest
clc;
clear;
x=sin(pi*[0:0.01:10]);
plot(x);
%{% text(3*pi/4,sin(3*pi/4),...
% ['sin(3*pi/4) = ',num2str(sin(3*pi/4))],...
% 'HorizontalAlignment','center',...
% 'BackgroundColor',[.7 .9 .7]);%%}%
text(600,0,'hi') D.S. Aldar K.B.P.C.O.E.P Satara 31
Controlling the command window
echo- Echo commands in M-files.
echo ON - turns on echoing of commands inside Script-files.
echo OFF - turns off echoing.
echo file ON- where 'file' is a function name causes the named Function-file to be
echoed when it is used.
echo file OFF -turns it off.
echo file - toggles it.
echo ON ALL - turns on the echoing of commands inside anyFunction-files that
are currently in memory (i.e., the functions returned by INMEM).
echo OFF ALL - turns them all off.

more Control paged output in command window.


more OFF - disables paging of the output in the MATLAB command window.
more ON - enables paging of the output in the MATLAB command window.
more(N) - specifies the size of the page to be N lines. 32
Controlling the command window
DIARY FILENAME causes a copy of all subsequent command window input
and most of the resulting command window output to be appended to the
named file. If no file is specified, the file 'diary' is used.
DIARY OFF: suspends it.
DIARY ON: turns it back on.
DIARY: by itself, toggles the diary state.
Use the functional form of DIARY, such as DIARY('file'),
when the file name is stored in a string.

beep Produce beep sound.


beep -produces a beep sound.
beep ON - turns the beep on.
beep OFF - turns the beep off.
S = beep - returns the beep status: 'on' or 'off'.

D.S. Aldar K.B.P.C.O.E.P Satara 33


Special Character
colon - Colon :
paren - Parentheses and subscripting ()
paren - Brackets []
paren - Braces and subscripting {}
punct - Function handle creation @
punct - Decimal point .
punct - Structure field access .
punct - Parent directory ..
punct - Continuation ...
punct - Separator ,
punct - Semicolon ;
punct - Comment %
D.S. Aldar K.B.P.C.O.E.P Satara 34
Special Character

punct - Invoke operating system command !


punct - Assignment =
punct - Quote '
transpose - Transpose .'
ctranspose - Complex conjugate transpose '
horzcat - Horizontal concatenation [,]
vertcat - Vertical concatenation [;]
subsasgn - Subscripted assignment ( ),{ },.
subsref - Subscripted reference ( ),{ },.
subsindex - Subscript index
Cont..
D.S. Aldar K.B.P.C.O.E.P Satara 35
General Purpose functions
General information:
helpbrowser - Bring up the help browser.
doc - Complete on-line help, displayed in the help browse.
help - M-file help, displayed at the command line.
helpwin - M-file help, displayed in the help browser.
helpdesk - Full product family help.
lookfor - Search all M-files for keyword.
syntax - Help on MATLAB command syntax.
support - Open MathWorks Technical Support Web Page.
demo - Run demonstrations.
ver - MATLAB, SIMULINK, and toolbox version information.
version - MATLAB version information.
whatsnew - Access Release Notes. cont.. 36
General Purpose functions
Some more functions.
path - Get/set search path.
addpath - Add directory to search path.
rmpath - Remove directory from search path.
echo - Echo commands in M-files.
format - Set output format.
beep - Produce beep sound.
cd - Change current working directory.
copyfile - Copy a file or directory.
movefile - Move a file or directory.
pwd - Show (print) current working directory.
dir - List directory.
D.S. Aldar K.B.P.C.O.E.P Satara 37
Number Display Format
FORMAT SHORT Scaled fixed point format with 5 digits.
FORMAT LONG Scaled fixed point format with 15 digits for double
and 7 digits for single.
FORMAT SHORT E Floating point format with 5 digits.
FORMAT LONG E Floating point format with 15 digits for double and
7 digits for single.
FORMAT SHORT G Best of fixed or floating point format with 5 digits.
FORMAT LONG G Best of fixed or floating point format with 15 digits
for double and 7 digits for single.
FORMAT HEX Hexadecimal format.
FORMAT + The symbols +, - and blank are printed
for positive, negative and zero elements.
Imaginary parts are ignored.
FORMAT BANK Fixed format for dollars and cents.
FORMAT RAT Approximation by ratio of small integers.

e.g. pi
D.S. Aldar K.B.P.C.O.E.P Satara 38
Numbers in MATLAB
• MATLAB uses conventional decimal notation for
numbers.

For Example:
3, -99, 0.0001, 3.14159, 1.60210e-20, 6.02252e23, 1i, 1j
3e5i
• All numbers are stored using the long format specified
by the double precision 64- bit IEEE floating-point
standard (i.e. 8 bytes). Floating-point numbers have a
finite precision of roughly 16 significant decimal digits
and a finite range of roughly 10-308 to 10+308.
D.S. Aldar K.B.P.C.O.E.P Satara 39
Complex Numbers
>> c1=1-2i % j also works
c1 =
1.0000 - 2.0000i
>> c1=complex(1,-2)
c1 =
1.0000 - 2.0000i
>> c2=3*(2-sqrt(-1)*3)
c2 =
6.0000 - 9.0000i
>> c3=sqrt(-2)
c3 =
0 + 1.4142i D.S. Aldar K.B.P.C.O.E.P Satara 40
Arithmetic Operators
Let p=3, q=2, L=[ 1 1-j ] ;

OPERATOR OPERATION ALGEBRAIC MATLAB FORM RESULT OF


FORM EXPRESSION
+ Addition p+q p+q 5
- Subtraction p-q p-q 1
.* Multiplication (Element pXq p .* q 6
by Element)
./ Right Division (Element p/q p ./ q 1.5
by Element)
.\ Left Division ( Element q X p-1 p .\ q 0.6667
by Element)
.^ Exponentiation pq p.^q 9
(Element by Element)
' Complex conjugate LH L' 1
transpose 1+1i
.' Transpose LT L.' 1
1–1i
Relational Operators
Let p=3, q=2

OPERATOR OPERATION RELATIONAL MATLAB FORM RESULT OF


FORM EXPRESSION
< Less than p<q p<q 0 i.e. false
<= Less than or equal to p≤q p <= q 0
> Greater than p>q p>q 1 i.e true
>= Greater than or equal to p≥q p >= q 1
== Equal to p=q p == q 0
~= Not equal to p≠q p ~= q 1

D.S. Aldar K.B.P.C.O.E.P Satara 42


Logical Operators

OPERATOR FUNCTION DESCRIPTION MATLAB FORM RESULT OF


EXPRESSION
& - &(and) returns 1 if both A&B 1
elements are true
| - |(or) returns 1 if either one A|B 1
of the element is true
~ - ~(not) complements the ~C 0
element ‘a’ and returns ‘-a’
- xor ( ) Returns 1 if only one of the xor(A,B) 0
element is true
- any ( ) True if any element of any(A) 1
vector is nonzero
- all ( ) True if all elements of all(A) 1
vector are nonzero
D.S. Aldar K.B.P.C.O.E.P Satara 43
Bitwise operators.
bitand - Bit-wise AND.
e.g
A = uint8([0 1; 0 1])
B = uint8([0 0; 1 1])
TT = bitand(A,B)

bitcmp - Complement bits.


>> A = uint8([0 1; 0 1])
A=
0 1
0 1
>> bitcmp(A)
ans =
255 254
255 254

D.S. Aldar K.B.P.C.O.E.P Satara 44


Bitwise operators.
bitor - Bit-wise OR.
bitxor - Bit-wise XOR.
bitset - Set bit. { C = BITSET(A,BIT) sets bit position BIT
in A to 1 (on)}
bitget - Get bit. {C = BITGET(A,BIT) returns the value of
the bit at position BIT in A. }
bitshift - Bit-wise shift.{ C = BITSHIFT(A,K,N),
i.e. Equivalant to C = fix(A*2^K)}

Example: Example:
A = uint8([0 1; 0 1]) A = uint8([0 1; 0 1])
B = uint8([0 0; 1 1]) B = uint8([0 0; 1 1])
C = bitxor(A,B) C = bitor(A,B)
D.S. Aldar K.B.P.C.O.E.P Satara 45
Order of precedence or Hierarchy of operations

PRECEDENCE OPERATION
First Parentheses, evaluated starting with innermost pair.
Second Exponentiation, evaluated from left to right
Third Multiplication and division with equal precedence,
evaluated from left to right
Fourth Addition and subtraction with equal precedence,
evaluated from left to right.

D.S. Aldar K.B.P.C.O.E.P Satara 46


Order of precedence for operator types

PRECEDENCE OPERATION
First Parentheses, evaluated starting with innermost pair.
Second Arithmetic operators and logical NOT(~); evaluated
from left to right
Third Relational operators; evaluated from left to right
Fourth Logical AND
Fifth Logical OR

D.S. Aldar K.B.P.C.O.E.P Satara 47


Creating vectors & Array
 A= initial value : increment : final value
e.g. a = 0:2:6 ; produces a =[0 2 4 6]

A= initial value : final value e.g. A=0:4; produces A=[0 1 2 3 4]


linspace - Linearly spaced vector.
X=linspace(first, last, n)
logspace - Logarithmically spaced vector.
X=logspace(first, last, n)

e.g.
b = linspace(0,20,5) , generates b = [0 5 10 15 20];
c = logspace(0,3,4), generates c = [1 10 100 1000].

i.e. 10.^(linspace(a,b,n))
D.S. Aldar K.B.P.C.O.E.P Satara 48
Arrays and Matrices
• a vector x = [1 2 5 1]

x =
1 2 5 1

• a matrix x = [1 2 3; 5 1 4; 3 2 -1]

x =
1 2 3
5 1 4
3 2 -1

• transpose y = x.’ y =
1
2
5 Cont..49
1
Arrays and Matrices
>> x=1:5 >> w=b'
w=
x= 1 2 3 4 5
1 2 3 4 5
>> c=x.'
>> b=x' c=
1
2
b=
3
4
1 5

2
3
4
5
D.S. Aldar K.B.P.C.O.E.P Satara Cont.. 50
Arrays and Matrices
>> d=complex(x,x)
d=
Columns 1 through 4
1.0000 + 1.0000i 2.0000 + 2.0000i 3.0000 + 3.0000i 4.0000 + 4.0000i
Column 5
5.0000 + 5.0000i

>> e=d'
e=
1.0000 - 1.0000i
2.0000 - 2.0000i
3.0000 - 3.0000i
4.0000 - 4.0000i
5.0000 - 5.0000i
D.S. Aldar K.B.P.C.O.E.P Satara 51
Arrays and Matrices
>> f=d.'
f=
1.0000 + 1.0000i
2.0000 + 2.0000i
3.0000 + 3.0000i
4.0000 + 4.0000i
5.0000 + 5.0000i
>> g=[1 2 3 4;5 6 7 8]

g=

1 2 3 4
5 6 7 8 D.S. Aldar K.B.P.C.O.E.P Satara 52
Arrays and Matrices
• x(i,j) subscription y=x(2,3)
y =
4
y=x(3,:)
• whole row y =
3 2 -1

y=x(:,2)
y = 2
• whole column 1
2
D.S. Aldar K.B.P.C.O.E.P Satara 53
Arrays and Matrices
>> A=[1 2 3 ... >> A(:,2)=[]
2 3] continuation = 1 3
4 6
A =[ 1 2 3 2 3] 5 7

If
IF 2 3 4 5 6
9 0 8 7 6 S =[1 4 ]
B= 8 0 9 7 6
4 5 0 7 6
>>A(2:3, :)= B(S,:) = 2 3 4 5 6
4 -5 6 4 5 0 7 6
5 -6 7
>> A(2:3,1:3) = B(: ,S) = 2 5
4 -5 6 9 7
5 -6 7 8 7
4 7

D.S. Aldar K.B.P.C.O.E.P Satara 54


Matrices in Matlab
>>A = [1, 2, 3, 4; 5, 6, 7, 8; 9, 10, 11, 12];
>>B = A([1,2], [3, 4]) >> a=[4 5 6;7 8 9]
>>B = a=
3 4 4 5 6
7 8 7 8 9
>> a(:)
>>A(3, [2 2 2])
ans =
10 10 10 4
7
5
>>A = [1, 2; 3, 4];
8
>>A(A >= 3) 6
3 9
4 D.S. Aldar K.B.P.C.O.E.P Satara 55
Indexing Matrices

•Index complete row or column using


the colon operator
•>> A(1,:)

•Can also add limit index range


•>> A(1:2,:)
•>> A([1 2],:)

•General notation for colon operator


•>> v=1:5
•>> w=1:2:5
D.S. Aldar K.B.P.C.O.E.P Satara 56
Indexing Matrices
>> A=[1,3,6;2,7,8;0,3,9];
>> A(:,1)+A(:,3)
ans =
7
10
9
>> A(1,:)+A(2,:)
ans =
3 10 14
D.S. Aldar K.B.P.C.O.E.P Satara 57
Missing Data
• Real life experiments often suffer from missing data - you may
want to exclude trials where reaction times fall outside some
limits, or where the subject made an error.
• In Matlab, you can do this using NaN. NaN stands for Not A
Number and can be used in any vector or matrix in place of
missing data.
• In general, it is much better to replace your missing data with
NaNs than to delete it altogether.
• When you use NaN, some of the basic functions like sum and
mean will no longer work as you expect, but Matlab provides
alternate versions, nansum, nanmean and nanstd which let
you ignore NaNs and find the sum, mean and standard
deviation of your data.
D.S. Aldar K.B.P.C.O.E.P Satara 58
Missing Data
>> data = [4 14 6 11 3 14 8 17 17 12 10 18];
>> cat = [1 3 2 1 2 2 3 1 3 2 3 1];
>> err = [1 0 0 0 0 0 0 1 0 1 0 0];
>> data(err==1) = NaN
data =
NaN 14 6 11 3 14 8 NaN 17 NaN 10 18
>> cat2 = cat==2
cat2 =
0 0 1 0 1 1 0 0 0 1 0 0
>> data2 = data(cat2)
data2 =
6 3 14 NaN
>> mdat2 = nanmean(data2)
mdat2 = 7.6667 D.S. Aldar K.B.P.C.O.E.P Satara 59
Multidimensional Arrays
 Multidimensional arrays in MATLAB are an extension of the normal two-
dimensional matrix. Matrices have two dimensions: the row dimension and
the column dimension.

 Multidimensional arrays use additional subscripts for indexing. A


three-dimensional array, for example, uses three subscripts:
• The first references array dimension 1, the row.
•The second references dimension 2, the column.
•The third references dimension 3.
This guide uses the concept of a page to represent dimensions 3
D.S. Aldar K.B.P.C.O.E.P Satara 60
and higher.
Multidimensional array

D.S. Aldar K.B.P.C.O.E.P Satara 61


Multidimensional array
To access the element in the second row, third column of page 2,
for example, you use the subscripts(2,3,2).

D.S. Aldar K.B.P.C.O.E.P Satara 62


Multidimensional array
>> c(: , : ,1)=[1 2 3; 4 5 7];
>> c(: , : ,2)=[3 2 1; 6 7 8];
>> whos c
Name Size Bytes Class
c 2x3x2 96 double array
Grand total is 12 elements using 96 bytes
>> c
c(: , : ,1) =
1 2 3
4 5 7
c(: , : ,2) =
3 2 1
6 7 8
D.S. Aldar K.B.P.C.O.E.P Satara 63
Generating Vectors from functions
x = zeros(1,3)
• zeros(M,N) MxN matrix of zeros x =
0 0 0

• ones(M,N) MxN matrix of ones x = ones(1,3)


x =
1 1 1

• rand(M,N) MxN matrix of uniformly


x = rand(1,3)
distributed random
numbers on (0,1) x =
0.9501 0.2311 0.6068
x = eye(2,3)
• eye(n,m) Generates n x m
x= 1 0 0
identity matrix
0 1 0
D.S. Aldar K.B.P.C.O.E.P Satara 64
Generating Vectors from functions
& other Matrix functions
•randn(M,N) MxN matrix of normally x = randn(1,3)
distributed random numbers x = 0.9501 0.2311 0.6068
•diag(b) generates the diagonal matrix
b= 2 3 4
9 0 8
8 0 9
•rot90(b) rotates a matrix „b‟ by 90 degree
diag(b)= 2 0 9

•fliplr(c) flip matrix from left to right rot90(b)= 4 8 9


3 0 0
•flipud(x) flip matrix from up/down 2 9 8
c = [2 3 4 5]
fliplr(c) = [5 4 3 2]

x= 14 becomes 3 6
25 25
D.S. Aldar K.B.P.C.O.E.P Satara 36 1 65
4
Generating Vectors from functions
& other Matrix functions
>> rand(1,4)
ans =
0.8147 0.9058 0.1270 0.9134
>> rand('state',0) rand(‘state’, seed)
>> rand(1,4)
ans =
0.9501 0.2311 0.6068 0.4860
>> rand('state',1234)
>> rand(1,4)
ans =
0.6104 0.8815 0.0209 0.0573

Also see randn(r,c)


D.S. Aldar K.B.P.C.O.E.P Satara 66
Generating Vectors from functions & other
useful Matrix functions
tril - Extract lower triangular part. If 1 2 3
triu - Extract lower triangular part A= 4 5 6
5 6 7
reshape - change size
tril(A)= 1 0 0
size - Size of array. 4 5 0
length - Length of vector. 5 6 7
det - Determinant triu(A)= 1 2 3
rank - Matrix rank 0 5 6
0 0 7
pascal - Pascal matrix
magic - Magic square If
min - Smallest component. a= 1 2 3
3 4 5
max - Largest component
randperm – random permutation reshape(a,3,2) = 1 4
p = randperm(n): returns a random 3 3
2 5
permutation of the integers 1:n.
D.S. Aldar K.B.P.C.O.E.P Satara 67
Matrix manipulation
>> A=magic(3) >> X = inv(A)
X=
A= 0.1472 -0.1444 0.0639
-0.0611 0.0222 0.1056
8 1 6
-0.0194 0.1889 -0.1028
3 5 7
4 9 2
>> sum(A)
ans =
15 15 15
>> det(A)
ans =
-360
D.S. Aldar K.B.P.C.O.E.P Satara 68
Matrix manipulation
SVD - Singular value decomposition.
S = SVD(X) - returns a vector containing the singular values
NORM Matrix or vector norm
NORM(X) - is the largest singular value of X, max(svd(X))

>> A=magic(3) >> e = eig(A)


A= e=
15.0000
8 1 6
4.8990
3 5 7 -4.8990
4 9 2 >>s = svd(A)
s=
>> r = norm(A)
15.0000
r= 6.9282
15 3.4641
D.S. Aldar K.B.P.C.O.E.P Satara 69
Matrix manipulation
ndims - Number of dimensions.
numel - NUMEL Number of elements in an array or
subscripted array expression.
>> A=[1 2 3; 4 5 6;3 5 6]
A=
1 2 3 >> a=[2:10]
4 5 6
3 5 6 a=
>> size(A)
ans = 2 3 4 5 6 7 8 9 10
3 3
>> ndims(A) % Which Gives dimension
>> length(a)
ans =
2
>> numel(A) %% Number of elements ans =
ans =
9
9
D.S. Aldar K.B.P.C.O.E.P Satara 70
Useful Matrix functions
sort - Sort in ascending order.
-- For vectors, sort(x) sorts the elements of x in ascending order.
-- For matrices, sort(x) sorts each column of x in ascending order.
sortrows - Sort rows in ascending order

y = sort(x,DIM,MODE)
has two optional parameters.
DIM - selects a dimension along which to sort.
MODE - selects the direction of the sort
'ascend' results in ascending order
'descend' results in descending order
The result is in y which has the same shape and type as x.

Cont..
D.S. Aldar K.B.P.C.O.E.P Satara 71
Useful Matrix functions
Exa:
A=[10 23 65 2 ;3 6 25 14;1 23 9 7] A= [ 3 7 5
>> sort(A) 6 8 3
ans = 0 4 2 ];
1 6 9 2 >> sort(A,'descend')
3 23 25 7 ans =
10 23 65 14 6 8 5
3 7 3
>> sortrows(A)
0 4 2
ans =
1 23 9 7
3 6 25 14
10 23 65 2

>> f=['once ';'upon ';'a ';'time ';'there';'lived';'three';'bears'];


>> sorted=sortrows(f);
>>sorted1=sort(f)

D.S. Aldar K.B.P.C.O.E.P Satara 72


Matrix and Array Operations
MATRIX OPERATIONS:
>> A = [1,2,3;4,-5,6;5,-6,7]
>> A + 2
ans = 3 4 5
6 -3 8
7 -4 9 B=A'
>> B = A’ B=
>> A*B 1 4 5
>> A+B 2 -5 -6
3 6 7
Note:
• Matlab is case-sensitive A+B
ans =
A and a are two different variables
2 6 8
• Transponate conjugates complex 6 -10 0
entries; avoided by
8 0 14
>> B=A.’
D.S. Aldar K.B.P.C.O.E.P Satara 73
Matrix and Array Operations
ARRAY OPERATIONS:

Element by element multiplication


.*
Element by element left division
./
Element by element right division
.\
Element by element exponentiation
.^
.‟ Nonconjugated transpose

EX: 1. A=[1 2 3], B=[2 3 5]


>> A*B i.e Matrix Multiplication
??? Error using ==> mtimes
Inner matrix dimensions must agree.
D.S. Aldar K.B.P.C.O.E.P Satara 74
Matrix and Array Operations
>> A .*B i.e.Array multiplication
ans =
2 6 15

Ex: 2. A=[1-i 2+2j 3-2j]


>> A'
ans =
1.0000 + 1.0000i
2.0000 - 2.0000i
3.0000 + 2.0000i
>> A .'
ans =
1.0000 - 1.0000i
2.0000 + 2.0000i
3.0000 - 2.0000i D.S. Aldar K.B.P.C.O.E.P Satara 75
Matrix operations
find function
>> A = [1, 3, 6; -3, 10, 50]
A=
1 3 6
-3 10 50
>>k = find(A < 0 | A >= 15)
k=
2
6
i.e. the 2nd and 6th elements of A(:) are < 0 or >= 15:

>> x=[1 4 6 3 2 1 6]
x=
1 4 6 3 2 1 6
>> m=max(x)
m=
6
>> i=find(x==m)
i=
3 7 D.S. Aldar K.B.P.C.O.E.P Satara 76
Matrices & Vector

>> d=[2 4 6 8];


>> d1=[-3 -3 -3];
>> d2=[-1 -1];
>> D=diag(d) + diag(d1,1) + diag(d2,-2)

D=
2 -3 0 0
0 4 -3 0
-1 0 6 -3
0 -1 0 8
D.S. Aldar K.B.P.C.O.E.P Satara 77
MATRIX & ARRAY MULTIPLICATION
MATRIX Multiplication ARRAY Multiplication
>> A=[2 5;6 4] C=[4 6 9]; D=[3 2 1];
A= >> C.*D
2 5
ans =
6 4
12 12 9
>> B=[2 6 9; 5 6 4]
B=
2 6 9 Array Division
5 6 4 >> C./D
>> A*B ans =
ans = 1.3333 3.0000 9.0000
29 42 38
32 60 70
>> C.\D
Let B =[2 5;6 6; 9 4]
>> A*B
ans =
??? Error using ==> mtimes 0.7500 0.3333 0.1111
78
Inner matrix dimensions must agree.
Array Preallocation
• Matlab's matrix variables have the ability to dynamically
augment rows and columns. For example,
>> a = 2;
>> a(2,6) = 1
a=
2 0 0 0 0 0
0 0 0 0 0 1

• Matlab automatically resizes the matrix. Internally, the matrix data memory
must be reallocated with larger size. If a matrix is resized repeatedly-like
within a loop-this overhead can be significant.
• To avoid frequent reallocations, preallocate the matrix with the zeros
command.

D.S. Aldar K.B.P.C.O.E.P Satara 79


MULTIPLICATION OF VECTORS
We know dot product of vectors i,j,k are
i.i=j.j=k.k=1 and i.j=i.k=j.k=0
The dot product in terms of unit vectors as
u.w = (u1i + u2j + u3k).(w1i + w2j + w3k)
Which gives
u.w = u1w1 + u2w2 + u3w3
Example: u=6i-8j+3k & w=5i+3j-4k Find u.w
>> u=[6 -8 3]; w=[5 3 -4];
>> dotp=sum(u.*w)
dotp =
-6

D.S. Aldar K.B.P.C.O.E.P Satara 80


MULTIPLICATION OF VECTORS

>> a=[1 2 3]
>> u=[6 -8 3]; w=[5 3 -4];
>> b=[4 5 6]
>> dot(u,w)
>> dot(a,b) ans =
ans = -6
32 >> cross(u,w)
>> cross(a,b) ans =
23 39 58
ans =
-3 6 -3

D.S. Aldar K.B.P.C.O.E.P Satara 81


MATRIX OPERATION
>> v=[10:2:20]
>> th=[50:10:80]
>> h=(v'.^2)*(sind(th).^2)/(2*9.8)
h=
2.9940 3.8265 4.5052 4.9482 0 50.0000 60.0000 70.0000 80.0000
4.3114 5.5102 6.4875 7.1254
5.8682 7.5000 8.8302 9.6985 10.0000 2.9940 3.8265 4.5052 4.9482
12.0000 4.3114 5.5102 6.4875 7.1254
7.6646 9.7959 11.5334 12.6674 14.0000 5.8682 7.5000 8.8302 9.6985
9.7006 12.3980 14.5969 16.0322 16.0000 7.6646 9.7959 11.5334 12.6674
11.9760 15.3061 18.0209 19.7928 18.0000 9.7006 12.3980 14.5969 16.0322
20.0000 11.9760 15.3061 18.0209 19.7928

>> tb=[0,th;v',h]
tb =
0 50.0000 60.0000 70.0000 80.0000
10.0000 2.9940 3.8265 4.5052 4.9482
12.0000 4.3114 5.5102 6.4875 7.1254
14.0000 5.8682 7.5000 8.8302 9.6985
16.0000 7.6646 9.7959 11.5334 12.6674
18.0000 9.7006 12.3980 14.5969 16.0322
82
20.0000 11.9760 15.3061 18.0209 19.7928
Predefined Special Values
Function Return Value
pi ,eps 3.1415926535897... , 2.2204e-016

inf Infinity. Calculations like n/0, where n is any nonzero real value,
result in inf. x = exp(1000) = Inf , x = 1.e1000 =Inf , x = log(0)= -Inf
NaN Not-a-Number, an invalid numeric value. Expressions like 0/0 and
inf/inf result in a NaN, as do arithmetic operations involving a NaN.
n/0, where n is complex, also returns NaN.
i,j Contains the value i (√-1).
date contains the current date in a character strings format, such as 17-
Feb-2007
Ans Most recent answer (variable). If you do not assign an output variable
to an expression, MATLAB automatically stores the result in ans.

clock Current date and time as date vector.


CLOCK = [year month day hour minute seconds]
83
Trigonometric Functions

D.S. Aldar K.B.P.C.O.E.P Satara 84


Trigonometric Functions

D.S. Aldar K.B.P.C.O.E.P Satara 85


Trigonometric Functions

86
Exponential Functions
•exp : Exponential
•expm1: Compute exp(x)-1 accurately for small values of x
•log : Natural logarithm
•log10: Common (base 10) logarithm
•log1p: Compute log(1+x) accurately for small values of x
•log2: Base 2 logarithm and dissect floating-point numbers into
exponent and mantissa
•nthroot: Real nth root of real numbers
•pow2: Base 2 power and scale floating-point numbers
•sqrt: Square root D.S. Aldar K.B.P.C.O.E.P Satara 87
Complex functions
Complex:
abs - Absolute value.
angle - Phase angle.
complex - Construct complex data from real and imaginary parts.
conj - Complex conjugate.
imag - Complex imaginary part.
real - Complex real part.
isreal - True for real array.
sign - Signum function
D.S. Aldar K.B.P.C.O.E.P Satara 88
Discrete Math Functions

D.S. Aldar K.B.P.C.O.E.P Satara 89


Rounding and remainder
Need of rounding & remainder
>> p=eps
>> 1-.5-.3-.2
p=
ans =
0 2.2204e-016
>> 1-.4-.4-.2
>> k=1-.4-.4-.2
ans =
-5.5511e-017 k=
>> 1-.5-.4-.1 -5.5511e-017
>> k<p
ans =
ans =
-2.7756e-017
1
>> eps
Here k<p, mean this error is negligible
ans =
but in complex application it can not be
2.2204e-016
ignored. Therefore whenever required
use rounding 90
Rounding and remainder
fix - Round towards zero.
e.g.
>> a=2.3
a=
2.3000
>> fix(a)
ans =
2
floor - Round towards minus infinity.
>> a=2.3
>> floor(a)
ans =
2
>> x=-2.3;
>> floor(x)
ans =
-3 D.S. Aldar K.B.P.C.O.E.P Satara 91
Rounding and remainder
ceil - Round towards plus infinity.
>> a=2.3
>> ceil(a)
ans =
3
>> x=-2.3;
>> ceil(x)
ans =
-2
round - Round towards nearest integer.
>> round(a)
ans =
2
>> round(x)
ans =
-2 D.S. Aldar K.B.P.C.O.E.P Satara 92
Rounding and remainder
mod - Modulus (signed remainder after division).

rem - Remainder after division.


>> rem(3,2)
ans =
1
sign - Signum function.
>> a=--5;
>> sign(a)
ans =
-1
>> x=5;
>> sign(a)
ans =
1 D.S. Aldar K.B.P.C.O.E.P Satara 93
Predefined Special Values
• Type date on command prompt
>> date
ans =
09-Jun-2008
>> dom = day('19-Dec-1994') % day of month
dom =
19
>> [n,m] = month('19-Dec-1994') % Month of date
n=
12
m=
Dec
y = year('19-Dec-1994') % Year of date
y=
1994 D.S. Aldar K.B.P.C.O.E.P Satara 94
Predefined Special Values
DATEVEC - Date components.
V = DATEVEC(N) - converts one or more date numbers N to date
vectors V
Examples:

d = '12/24/1984';
t = 725000.00;
c = datevec(d) or c = datevec(t) produce c = [1984 12 24 0 0 0].
[y,m,d,h,mi,s] = datevec(d) returns y=1984, m=12, d=24, h=0, mi=0, s=0.
c = datevec('5/6/03') produces c = [2003 5 6 0 0 0] until 2054.
c = datevec('5/6/03',1900) produces c = [1903 5 6 0 0 0].
c = datevec('19.05.2000','dd.mm.yyyy') produces c = [2000 5 19 0 0 0].

D.S. Aldar K.B.P.C.O.E.P Satara 95


Predefined Special Values
DATENUM - Serial date number.
N = DATENUM(V) converts one or more date vectors V into
serial date numbers N.

Examples:
n = datenum('19-May-2000') returns n = 730625.
n = datenum(2001,12,19) returns n = 731204.
n = datenum(2001,12,19,18,0,0) returns n = 731204.75.
n = datenum('19.05.2000','dd.mm.yyyy') returns n =
730625.75.
D.S. Aldar K.B.P.C.O.E.P Satara 96
Predefined Special Values
Now -Current date and time as date number.
>> now
ans =
7.3357e+005
>> d=fix(now)
d=
733568
>> day(d)
ans =
9
>> year(d)
ans =
2008
>> month(d)
ans =
6
D.S. Aldar K.B.P.C.O.E.P Satara 97
Predefined Special Values
• Colck : Current date and time as date vector.
CLOCK = [year month day hour minute seconds]
>> fix(clock)
ans =
2008 6 10 10 31 48
• >> inf/inf
ans =
NaN
• >> 0/0
Warning: Divide by zero.
ans =
NaN
D.S. Aldar K.B.P.C.O.E.P Satara 98
Predefined Special Values
>> x = 7i/0 >> x = 1/0
x = NaN + Infi x = Inf
>> NaN > NaN >> x = 1.e1000
ans = 0 x = Inf
>> x = exp(1000)
>> NaN ~= NaN x = Inf
ans = >> x = log(0)
1 x = -Inf

Because two NaNs are not equal to each other, logical operations involving NaN
always return false, except for a test for inequality, (NaN ~= NaN):

D.S. Aldar K.B.P.C.O.E.P Satara 99


Predefined Special Values
c = calendar(y,m), where y and m are integers, returns a
calendar for the specified month of the specified year.

Examples calendar(2007,2)
The command: calendar(1957,10) Feb 2007
reveals that the Space Age began on a S M Tu W Th F S
Friday (on October 4, 1957, when 0 0 0 0 1 2 3
Sputnik 1 was launched). 4 5 6 7 8 9 10
Oct 1957 11 12 13 14 15 16 17
S M Tu W Th F S 18 19 20 21 22 23 24
0 0 1 2 3 4 5 25 26 27 28 0 0 0
6 7 8 9 10 11 12 0 0 0 0 0 0 0
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31 0 0
0 0 0 0 0 0 0
D.S. Aldar K.B.P.C.O.E.P Satara 100
Predefined Special Values
>> calendar
>> calendar('19-dec-1994')
Dec 2008 Dec 1994
S M Tu W Th F S
S M Tu W Th F S
0 0 0 0 1 2 3
0 1 2 3 4 5 6 4 5 6 7 8 9 10
7 8 9 10 11 12 13 11 12 13 14 15 16 17
14 15 16 17 18 19 20 18 19 20 21 22 23 24
21 22 23 24 25 26 27 25 26 27 28 29 30 31
0 0 0 0 0 0 0
28 29 30 31 0 0 0
0 0 0 0 0 0 0
>> m = minute('19-Dec-1994, 13:25:08.17')
m=
25
>> h = hour('19-Dec-1994, 13:24:08.17')
h=
D.S. Aldar K.B.P.C.O.E.P Satara 101
13
Basic Data Analysis Function

FUNCTION DESCRIPTION
cumsum Cumulative Sum of elements
prod Product of elements
cumprod Cumulative products of elements
diff Difference function and approximate derivative
mean Average or Mean Value
median Median value
Std Standard deviation
trapz trapezoidal numerical integration
cumtrapz Cumulative trapezoidal numerical integration

D.S. Aldar K.B.P.C.O.E.P Satara 102


Cont..
Basic Data Analysis Function
>> a=[1 2 3 4];
>> cumsum(a) X = sort(rand(1,101)*pi);
Y = sin(X);
ans = Z = trapz(X,Y);
1 3 6 10 Z=
1.9984
>> prod(a)
ans =
24
>> cumprod(a)
ans =
1 2 6 24
>> mean(a)
ans =
2.5000 D.S. Aldar K.B.P.C.O.E.P Satara 103
Cartesian Coordinate System Conversion

• cart2pol: Transform Cartesian coordinates to polar or cylindrical


– Syntax : [THETA,RHO] = cart2pol(X,Y)

104
Cartesian Coordinate System Conversion
• cart2sph:Transform Cartesian coordinates to
spherical
– Syntax
[THETA,PHI,R] = cart2sph(X,Y,Z)

D.S. Aldar K.B.P.C.O.E.P Satara 105


Cartesian Coordinate System Conversion

• pol2cart:Transform polar or cylindrical coordinates to


Cartesian
– Syntax
[X,Y] = pol2cart(THETA,RHO)
[X,Y,Z] = pol2cart(THETA,RHO,Z)
• sph2cart :Transform spherical coordinates to Cartesian
– Syntax
[x,y,z] = sph2cart(THETA,PHI,R)

D.S. Aldar K.B.P.C.O.E.P Satara 106


Linear Equations
Example:-
6x+12y+4z=70; >>A=[6 12 4;7 -2 3;2 8 -9]
7x-2y+3z=5; >>B=[70;5;64]
2x+8y-9z=64; >> sol=A\B
Write Ax=B, where sol =
A= 6 12 4 3
7 -2 3 5
-2
2 8 -9
>>sol= inv(A)*B
X= x
sol =
y 3.0000
z 5.0000
B= 70 -2.0000
5
64
D.S. Aldar K.B.P.C.O.E.P Satara 107
EUCLIDEAN NORM
•The magnitude of vector v in three-dimensional space, having
components x,y,z,is
• It can be computed using matrix multiplication and transpose
as follows.

• norm(v) computes Euclidean norm


• Another function pinv (pseudoinverse) gives the minimum
value of the Euclidean norm, which is the magnitude of the
solution vector x.
•To solve set Ax=b ,type x=pinv(A)*b.

D.S. Aldar K.B.P.C.O.E.P Satara 108


EUCLIDEAN NORM
Obtain the solution to the following using the left division
method/inv and the pseudoinverse method.
x1+x2 +x3 = 400 --------------- (1)
10x1+5x2 =1600 -------------- (2)

>>A=[1 1 1; 10 5 0]; >> x=pinv(A)*b


>>b=[400;1600]; x=
>>rank(A) 93.3333
ans = 133.3333
2 173.3333
>> x=A\b
x=
160.0000 To understand how this is been
0 computed refer next slide
240.0000

109
D.S. Aldar K.B.P.C.O.E.P Satara
EUCLIDEAN NORM

 We can solve eq.1 & eq.2 to obtain x1 and x2 in terms of x3


as x1=x3-80 and x2=480-2x3. Then the Euclidean norm can be
expressed as

 The real value of x3 that minimizes n can be found by using


calculus or plotting N verses x3

 The answer is x3=173.3333 the same as minimum norm


solution given by the pseudoinverse method

D.S. Aldar K.B.P.C.O.E.P Satara 110


Reduced row echelon form
• From the last slide, we wrote the solutions for two of the
unknowns in terms of the third: x1=x3-80 and x2=480-2x3.
These two equations are equal to x1-x3=-80 , x2+2x3=480 .
In matrix form

• The augmented matrix [A b] for the above set is

• Note that first two columns form a 2 X 2 identity matrix.


This indicates that this can be solved directly for x1 and x2
in terms of x3.
• We can always reduce an underdetermined set, a
procedure for reducing an equation set to this form, which is
called the reduced row echelon form.
D.S. Aldar K.B.P.C.O.E.P Satara 111
Reduced row echelon form
rref: Reduced row echelon form
Syntax: R = rref(A) , [R,jb] = rref(A), [R,jb] = rref(A,tol)
Example: 2x1 -4x2 +5x3 = -4
-4x1 -2x2 +3x3 =4
2x1 +6x2 -8x3 = 0
Sol:
>> A=[2 -4 5;-4 -2 3;2 6 -8];
>> b=[-4;4;0];
>> rref([A b])
ans =
1.0000 0 -0.1000 -1.2000
0 1.0000 -1.3000 0.4000
0 0 0 0
The equations are x1 + 0x2 -0.1x3 = -1.2
0x1 +x2 +1.3x3 =0.4
0x1 +0x2 -0x3 = 0
D.S. Aldar K.B.P.C.O.E.P Satara 112
Polynomial operation using arrays
ROOTS Find polynomial roots.
ROOTS(C) computes the roots of the polynomial whose coefficients are the elements of the
vector C. If C has N+1 components,
the polynomial is C(1)*X^N + ... + C(N)*X + C(N+1)
Exa:
b =[1 -7 40 -34]
>> roots(b)
ans =
3.0000 + 5.0000i
3.0000 - 5.0000i
1.0000

D.S. Aldar K.B.P.C.O.E.P Satara 113


Polynomial operation using arrays
POLY - Convert roots to polynomial.
POLY(A), when A is an N by N matrix, is a row vector with
N+1 elements which are the coefficients of the
characteristic polynomial, DET(lambda*EYE(SIZE(A))
- A) .
Example:-
>> poly([1,3+5i,3-5i])
ans =
1 -7 40 -34

D.S. Aldar K.B.P.C.O.E.P Satara 114


Polynomial Evaluation

POLYVAL -Evaluate polynomial.


polyval(c,s): c is vector whose element are coefficients of pollynomial, s is
value at which polynomial is to be evaluated.

Example: Evaluate the polynomial y=2s2 + 3s + 4 at s = -1, -3

For s=-1,
for s=-3
>> y=[2 3 4];
>> s=-1;
>> y=[2 3 4];
>> v=polyval(y,s)
>> s=-3;
>> v=polyval(y,s)
v=
v=
3
13

D.S. Aldar K.B.P.C.O.E.P Satara 115


Polynomial product
f(x)g(x)=(9x3 -5x2 +3x+7)(6x2 - x + 2)
=54x5 -39x4 +41x3 +29x2 -x +14
To Find the product use conv function
>> f=[9 -5 3 7];
>> g=[6 -1 2];
>> product=conv(f,g)
product =
54 -39 41 29 -1 14
D.S. Aldar K.B.P.C.O.E.P Satara 116
Polynomial division
f(x) = 9x3 -5x2 +3x+7 and g(x) = 6x2 - x + 2

f(x)/g(x)= 1.5x-.5833

To Find the division use deconv function


>> f=[9 -5 3 7];
>> g=[6 -1 2];
>> [quotiont,reminder] =deconv(f,g)
quotiont =
1.5000 -0.5833
reminder =
0 0 -0.5833 8.1667
D.S. Aldar K.B.P.C.O.E.P Satara 117
Polynomial Differentiation
polyder: Polynomial derivative
dydx= polyder(p) :returns the derivative of the polynomial p.
dydx = polyder(a,b) returns the derivative of the product of the
polynomials a and b.
Exa: y= s4 + 4s3 + 8s2 + 16 The derivative of the product

>> y=[1 4 8 0 16]; >> a=[3 6 9];


>> dydx=polyder(y) >> b=[1 2 0];
>> k=polyder(a,b)
dydx =
k=
4 12 16 0
12 36 42 18

i.e.
D.S. Aldar K.B.P.C.O.E.P Satara 118
Polynomial Integration
polyint: Integrate polynomial analytically
polyint(p,k) : returns a polynomial representing the integral of
polynomial p, using a scalar constant of integration k.
polyint(p) : assumes a constant of integration k=0.
Example: Integrate the polynomial y=4s3 + 12s2 + 16s + 1, Take contant
of integration as 3.
>> y=[4 12 16 1];
Exa: y= s2 + s + 3
>> x=polyint(y,3)
x= >> y=[1 1 1];
1 4 8 1 3 >> x= polyint(y)
i.e. x = s4 +4s3 + 8s2 + s + 3. x=
0.3333 0.5000 1.0000 0
i.e. x= 033s2 + 0.50s2 + 3s
D.S. Aldar K.B.P.C.O.E.P Satara 119
Polynomial Curve Fitting
polyfit: Polynomial curve fitting
p = polyfit(x,y,n) : finds the coefficients of a polynomial p(x) of degree n that fits
the data, p(x(i)) to y(i), in a least squares sense. The result p is a
row vector of length n+1 containing the polynomial
coefficients in descending powers

Example: Find polynomial of degree 2 to fit the following data


x 0 1 2 4
y 1 6 20 100
>> x=[0 1 2 4];
>> y=[1 6 20 100];
>> c=polyfit(x,y,2)

c=
7.3409 -4.8409 1.6818

D.S. Aldar K.B.P.C.O.E.P Satara 120


Polynomial Curve Fitting
Example: Find polynomial of degree 1 to fit the following data
Current 10 15 20 25 30
Voltage 100 150 200 250 300

>> current=[10 15 20 25 30];


>> voltage=[100 150 200 250 300];
>> Res=polyfit(current,voltage,1)

Res =

10 0
i.e. voltage = 10 X current

D.S. Aldar K.B.P.C.O.E.P Satara 121


Character and String Constants
• Character constants can be single character
constants, string constants or escape sequence
constants.
• A string constant is a sequence of characters
enclosed in pair of single quotes.
• The characters may be alphabets, numbers,
special characters or blank spaces.
• It may be noted that space is also a character.
• Example:
‘Nice’ ‘2009’ ‘Best Luck’ ‘H1N1’

D.S. Aldar K.B.P.C.O.E.P Satara 122


String Construction
>> t='how are you?'
t=
how are you?

>> size(t)
ans =
1 12

>> whos
Name Size Bytes Class

ans 1x2 16 double array


t 1x12 24 char array

Grand total is 14 elements using 40 bytes


D.S. Aldar K.B.P.C.O.E.P Satara 123
String Construction
>>u= double(t)
u=
104 111 119 32 97 114 101 32 121 111 117 63
>> abs(t)
ans =
104 111 119 32 97 114 101 32 121 111 117 63
>> char(u)
ans =
how are you?

Note: Numerical Value less than 0 produces warning message when


converted to character, value greater than 255 simply address
characters in the front beyond char(255);
D.S. Aldar K.B.P.C.O.E.P Satara 124
String Construction
a=double('a') >> char(a)
a= ans =
97 Ab
>> a=double('b') >> t='how are you?';
a= >> x=t(5:7)
x=
98
Are
>> a=double('aa') >> x=t(7:-1:5)
a= x=
97 97 Era
>> a=double('ab') >> x=t(5:7)'
a= x=
97 98 a
r
e
D.S. Aldar K.B.P.C.O.E.P Satara 125
String Construction
>> t='don't leave that place?'
>> p='i will help you,'
??? t='don't leave that place?' >> q=‘ if you listen me'
| >> z=[p q]
z=
Error: Missing MATLAB
i will help you, if you listen me
operator.

>> t='don''t leave that place?'


t=
don't leave that place?

D.S. Aldar K.B.P.C.O.E.P Satara 126


String Construction
>> f=('once ','upon ','a ','time ','there','lived','three','bears');
??? f=('once ','upon ','a ','time ','there','lived','three','bears');
|
Error: Incomplete or misformed expression or statement.
>> f=char('once ','upon ','a ','time ','there','lived','three','bears')
f=
once
upon
a
time
there
lived
three
bears D.S. Aldar K.B.P.C.O.E.P Satara 127
String Construction
STRVCAT - Vertically concatenate strings.
>> f=char('once ','upon ','a','','time ')
f=
once
upon
a

time

>> f=strvcat('once ','upon ','a','','time ')


f=
once
upon
a
time
D.S. Aldar K.B.P.C.O.E.P Satara 128
String Construction
STRCAT - Concatenate strings.
>> a=char('apple', 'bananas')
a=
apple
bananas

>> b=char('oranges', 'grapes')


b=
oranges
grapes

>> strcat(a,b)
ans =
appleoranges
bananasgrapes
D.S. Aldar K.B.P.C.O.E.P Satara 129
String Functions
FINDSTR -Find one string within another.
>> b='ramu went to mumbai to serch destiny‘
>> findstr(b,' ')
ans =
5 10 13 20 23 29
>> findstr(b,'t')
ans =
9 11 21 33
>> findstr(b,'to')
ans =
11 21
D.S. Aldar K.B.P.C.O.E.P Satara 130
String Functions
>> c='a2:b_c' >> s= char('apple','banana','peach','mango','pineaple')
c= s=
a2:b_c apple
banana
>> ischar(c)
peach
ans = mango
1 Pineaple
>> isletter(c) >> strmatch('pe',s) % pe is in third row
ans = ans =
3
1 0 0 1 0 1
>> strmatch('banana',s)

ans =

D.S. Aldar K.B.P.C.O.E.P Satara 131


String Functions
LOWER - Convert string to lowercase.
UPPER - Convert string to uppercase.
>> a='hello'
>> upper(a)
ans =
HELLO
>> b='KBP SATARA'
>> lower(b)
ans =
kbp satara
D.S. Aldar K.B.P.C.O.E.P Satara 132
NUMBER TO STRING TO NUMBER
INT2STR - Convert integer to string.
NUM2STR - Convert numbers to a string.
MAT2STR - Convert a 2-D matrix to a string in MATLAB syntax.

>> a=eye(3) >> whos


a= Name Size Bytes Class
1 0 0
0 1 0 a 3x3 72 double array
0 0 1 b 3x7 42 char array
>> b=int2str(eye(3))
b=
1 0 0
0 1 0
0 0 1

D.S. Aldar K.B.P.C.O.E.P Satara 133


NUMBER TO STRING TO NUMBER
>> num2str(rand(2,4))
ans =
0.93547 0.41027 0.057891 0.81317
0.9169 0.89365 0.35287 0.0098613

>> mat2str(pi*eye(2)) % convert to MATLAB input systax form


ans =
[3.14159265358979 0; 0 3.14159265358979]

D.S. Aldar K.B.P.C.O.E.P Satara 134


NUMBER TO STRING TO NUMBER
FPRINTF -Write formatted data to file.
fprintf(format,data) – is used to convert numerical result to ASCII format.
FORMAT STRING RESULTS
%d Display value as an integer
%f Display value in floating format
%e Display value in exponential format
%g Display value in either exponential or floating point format,
Whichever is shortest
\n Skip to new line
\t Horizontal tab

>> fprintf('the value of pi is %6.2f \n',pi) % floating point in six character wide
the value of pi is 3.14
>> fprintf('the value of pi is %8.2f \n',pi) % eight character wide with line feed
the value of pi is 3.14 D.S. Aldar K.B.P.C.O.E.P Satara 135
NUMBER TO STRING TO NUMBER
• sprintf: Write formatted data to string
[s, errmsg] = sprintf(format, A, ...)

136
CELL ARRAYS
• A cell array is an array of cells i.e. each element is bin, or cell.
• Each cell stores an array.
• The elements of an array in a cell are all of the same type
but two different cell may have different type of elements.
• All rows in string must have same column is sometime
cumbersome, this is eliminated using cell array.
• Cell array is simply a data type that allows you to name a
group of data of various sizes & types.
• For example, One cell of a array might contain array of
numeric values, another cell may contain an array of text
strings, and the third cell may store an array of complex
values.
D.S. Aldar K.B.P.C.O.E.P Satara 137
Cell Arrays of Strings
>> c={'how';'about';'this for a'; 'cell array of string'}
c=
'how'
'about'
'this for a'
'cell array of string' >> c(4)
>> size(c) ans =
ans = 'cell array of string'
4 1 >> c{4}
>> c(1) ans =
ans = cell array of string
'how'

D.S. Aldar K.B.P.C.O.E.P Satara 138


Cell Arrays of Strings
C = {[1 2] 'Tony' 3+4i; [1 2;3 4] -5 'abc'};
celldisp(C)
C{1,1} =
1 2
C{2,1} = >> cellplot(C)
1 2
3 4
C{1,2} = Tony 3+4i

Tony
C{2,2} =
-5
C{1,3} = -5 abc

3.0000 + 4.0000i
C{2,3} =
D.S. Aldar K.B.P.C.O.E.P Satara 139
abc
Structure Array
• A structure array is an array of structures.
• A structure is a data type in which individual element
has a name.
• The individual element of structure are known as fields,
and each field in structure may have a different type.
• Each structure in the array will have identically the same
fields, but the data stored in each field can differ.
• The element in structures are accessed using named
fields.

D.S. Aldar K.B.P.C.O.E.P Satara 140


Sample structure

Student(1) Student(2)
Somesh Sansita Name
Name

Sadar Main street


Bazar Adrr1
Adrr1

City
City Godoli Shahunagar

Class
Class F.E. B.E.

141
Building structure
>> student.name='sansita'; >> student(1)
>> student.addr1='main street'; ans =
>> student.city='anytown'; name: 'sansita'
>> student addr1: 'main street'
city: 'anytown'
student =
name: 'sansita' >> student(2)
addr1: ' main street' ans =
city: 'anytown‘ name: 'somesh'
>> student(2).name='somesh' addr1: []
city: []
student =
1x2 struct array with fields:
name
addr1
city
D.S. Aldar K.B.P.C.O.E.P Satara 142
Matlab Programming and Data Types

 MATLAB provides a full programming language that enables


us to write a series of MATLAB statements into a file and then
execute them with a single command.
 we can write your program in an ordinary text file, giving the
file a name of filename.m.
 The term we use for filename becomes the new command that
MATLAB associates with the program. The file extension of .m
makes this a MATLAB M-file.
 M-files can be scripts that simply execute a series of MATLAB
statements, or they can be functions that also accept arguments and
produce output.
We can create M-files using a text editor, then use
them as you would any other MATLAB function or command.
D.S. Aldar K.B.P.C.O.E.P Satara 143
MATLAB Data Types
• There are 15 fundamental data types in MATLAB. Each of these
data types is in the form of a matrix or array. This matrix or array
is a minimum of 0-by-0 in size and can grow to an n-dimensional
array of any size.

D.S. Aldar K.B.P.C.O.E.P Satara 144


INTEGER DATA TYPE
MATLAB supports signed and unsigned integer data types having 8-,16-,32-, and 64-
bit lengths.
Data type Description
uint8 Unsigned 8-bit in the range 0 to 255(or 0 to 28)
int8 Signed 8-bit integer in the range -128 to 127(or -27 to 27-1)
uint16 Unsigned 16-bit in the range 0 to 65,535(or 0 to 216)
int16 Signed 16-bit integer in the range -32,768 to 32,767(or-215 to 215-1)
uint32 Unsigned 32-bit in the range 0 to 4,294,967,295(or 0 to 232)
int32 Signed 32-bit integer in the range -2,147,483,648 to 2,147,483,647
(or-231 to 231-1)
uint64 Unsigned 64-bit in the range 0 to 18,446,744,073,707,557,615
(or 0 to 264)
int64 Signed 64-bit integer in the range -9,223,372,036,854,775,808 to
9,223,372,036,854,775,808(or-263 to 263-1) 145
Floating-Point Numbers
Double-Precision Floating Point
 MATLAB constructs the double-precision (or double) data
type according to IEEE Standard 754 for double precision.
 Any value stored as a double requires 64 bits, formatted
as shown

D.S. Aldar K.B.P.C.O.E.P Satara 146


Floating-Point Numbers

Single-Precision Floating Point


 MATLAB constructs the single-precision (or single) data
type according to IEEE Standard 754 for single precision.
 Any value stored as a single requires 32 bits, formatted as
shown

D.S. Aldar K.B.P.C.O.E.P Satara 147


Floating-Point Arithmetic
Largest positive floating point number
• In almost all cases, numerical values in MATLAB are represented
in double precision arithmetic, using a binary (base 2)
representation internally.
• Such representation is the most common representation used by
computers and is a native format for numerical coprocessors.
• Because of this representation, not all numbers can be
represented exactly.
The largest positive number that can be handled by MATLAB is
>> format long
>>realmax(„single‟)
>> realmax ans =
ans = 3.4028235e+038
1.797693134862316e+308 >> realmin('single')
>> realmin ans =
ans = 1.1754944e-038
2.225073858507201e-308
148
Numbers Representation
Bitmax: Maximum double precision floating point integer.
BITMAX returns the maximum unsigned double precision floating point
integer. It is the value when all bits in the mantissa are set, 2^53-1.
Example:
Display in different formats the largest floating point integer
and the largest 32 bit unsigned integer.
>> format long e
>> bitmax >> format hex
ans = >> bitmax
ans =
9.007199254740991e+015 433fffffffffffff
>> intmax('uint32') >> intmax('uint32')
ans = ans =
4294967295 ffffffff

D.S. Aldar K.B.P.C.O.E.P Satara 149


Maximum Numbers
INTMAX Largest positive integer value.
X = INTMAX is the largest positive value representable in an int32.
Any value that is larger than INTMAX will saturate to INTMAX when
cast to int32.
>> intmax
ans =
2147483647
>> intmax('int32')
ans =
2147483647
>> intmax('int8')
ans =
127
>> intmax('int64')
ans =
9223372036854775807 D.S. Aldar K.B.P.C.O.E.P Satara 150
MATLAB m-files
Two types of m-files
1. Script files:
 collection of commands that Matlab executes
 Are useful for automating a series of steps you need to
perform many times.
 Do not accept input arguments or return output arguments.
 Store variables in a workspace that is shared with other
scripts and with the MATLAB command line interface.
2.Function files:
 Are useful for extending the MATLAB language for your
application.
 Can accept input arguments and return output arguments.
 Store variables in a workspace internal to the function.
Both types are separate files with a “.m” extension
D.S. Aldar K.B.P.C.O.E.P Satara 151
Variables declaration & File name
• MATLAB variable & file names must begin with a
letter, which may be followed by any combination of
letters, digits, and underscores.
• MATLAB distinguishes between uppercase and
lowercase characters, so A and a are not the same
variable.
• When naming variable & file, make sure you are not
using a name that is already used as a function name.
• Variable name may be 63 character long.
>> len = namelengthmax
len = 63
D.S. Aldar K.B.P.C.O.E.P Satara 152
MATLAB VARIABLES

• Local Variables:
• The variable defined & used in individual file
& command prompt.
• Local variable share the local workspace.
•Global Variables:
• The variable used among the different functions and files
• MATLAB functions exchange the data with the base
workspace through global memory.
• Global Memory is a special type of memory that can be
accessed form any workspace.
• The syntax to declare the variable A, X, and Q is
global A X Q.
• Use a space, not a comma, to separate variables
D.S. Aldar K.B.P.C.O.E.P Satara 153
Keywords
>> iskeyword

D.S. Aldar K.B.P.C.O.E.P Satara 154


The exist Function

• ident = exist( „item‟, „kind‟ )


checks the existing of „item‟
– item: name of the item to search for
– kind: optional value for restricting the search
for a specific kind of item (possible values are
„var‟, „file‟, „builtin‟, „dir‟)
– ident: a value based on the type of the item

D.S. Aldar K.B.P.C.O.E.P Satara 155


The exist Function
EXIST - Check if variables or functions are defined.
EXIST('A') returns:
0 - if A does not exist
1 - if A is a variable in the workspace
2 - if A is an M-file on MATLAB's search path. It also returns 2
when A is the full pathname to a file or when A is the name of an
ordinary file on MATLAB's search path
3 - if A is a MEX-file on MATLAB's search path
4 - if A is a MDL-file on MATLAB's search path
5 - if A is a built-in MATLAB function
6 - if A is a P-file on MATLAB's search path
7 - if A is a directory
8 - if A is a Java class

D.S. Aldar K.B.P.C.O.E.P Satara 156


MATLAB m-files
To create an m-file, open the Matlab text editor

Click on the “page” icon

The Matlab text editor window will open

D.S. Aldar K.B.P.C.O.E.P Satara 157


MATLAB m-files
Script Files
On the command line In the script file named test.m

>>x=3.0;
>>y=x^2;
>>y
y =
9.0

On the command line

>>test
y =
•Script files share the workspace memory 9.0
D.S. Aldar K.B.P.C.O.E.P Satara 158
MATLAB m-files
Function Files
• Matlab identifies function files from script files by using
the “function” and “return” keywords

•The name of the function file must be the same name as the
function
D.S. Aldar K.B.P.C.O.E.P Satara 159
Function Files
The function file x2.m

>>r=3; >>h=x2(4.2);
>>d=x2(r); >>h
>>d h =
d = 17.64
9.0

D.S. Aldar K.B.P.C.O.E.P Satara 160


Function Files
• Multiple Inputs and Outputs

outputs in square brackets [ ] inputs in parentheses ( )


D.S. Aldar K.B.P.C.O.E.P Satara 161
Matlab functions & User defined function

function [output variables] = function name(input variables)

Ex:
function f=myfunction(x,y)
f=x+y;

• save it in myfunction.m
• call it with y=myfunction(x,y)

D.S. Aldar K.B.P.C.O.E.P Satara 162


Matlab functions & User defined function

Exa:
function [ radius, theta] = myfunc( x, y)

% this is a comment, just like // in C++


% now create and evaluate theta (in radians)
theta = atan2(y,x);
% now create and evaluate radius
radius = sqrt( x.^2 + y.^2);

D.S. Aldar K.B.P.C.O.E.P Satara 163


Optional Argument
nargin & nargout - nargin and nargout indicate how many input
or output arguments, respectively, a user has supplied. Outside the
body of a function M-file, nargin and nargout indicate the number of
input or output arguments, respectively, for a given function. The
number of arguments is negative if the function has a variable number
of arguments.
nargchk –The nargchk function often is used inside an M-file to
check that the correct number of arguments have been passed.

MSGSTRUCT = NARGCHK(LOW,HIGH,N,'struct') returns an


appropriate error message structure if N is not between LOW and
HIGH. If N is in the specified range, the message structure is empty.
The message structure has at a minimum two fields, 'message' and
'identifier'.
D.S. Aldar K.B.P.C.O.E.P Satara 164
Optional Argument
error – Display message and abort function
ERROR('MSGID', 'MESSAGE') displays the error message in
the string MESSAGE, and causes an error exit from the
currently executing M-file to the keyboard.

warning - Display warning message


WARNING('MESSAGE') displays the warning message
MESSAGE, unless it has been disabled (see the special
identifier 'all' in "Controlling Warning Message Display"
below).
D.S. Aldar K.B.P.C.O.E.P Satara 165
Function with help & nargin
function[y,z]=hello(a,b)
% this compute adition & substration of 2 nos

if (nargin < 2 |nargin > 2 )


error('number arguments should be two');
end;
y=a+b; >> hello(2,3,4)
z=a-b; ??? Error using ==> hello
return Too many input arguments.
>> hello(2)
??? Error using ==> hello
Type on command prompt number arguments should be two

>> help hello


this compute adition & substration of 2 nos
D.S. Aldar K.B.P.C.O.E.P Satara 166
Function with narchk
function[y,z]=hello(a,b)
% this compute aditin & substration of 2
nos
error(nargchk(1, 3, nargin, 'struct'))
y=a+b;
z=a-b;
return Type on command prompt

>> hello
??? Error using ==> hello
Not enough input arguments.
>> hello(2,3,5)
??? Error using ==> hello
Too many input arguments.

D.S. Aldar K.B.P.C.O.E.P Satara 167


Subfunctions
•Function M-files can contain code for more than one function.
• The first function in the file is the primary function, the function invoked
with the M-file name.
•Additional functions within the file are subfunctions that are only visible
to the primary function or other subfunctions in the same file.

File result.m Functions result are


only accessible
from outside the file
result

pcent Functions pcent


and divs are
only accessible
divs from Inside the file

168
Subfunctions
function[percent,division]=result(marks)
% result calculates percentages & division
n=length(marks);
percent=pcent(marks,n);
division=divs(percent,n);
function percent=pcent(marks,n);
% calculate percentage
percent=sum(marks)/n;
function d=divs(p,n)
% calculate the division
if p>60
d='first class';
else
d='pass class or second class';
end;
D.S. Aldar K.B.P.C.O.E.P Satara 169
Subfunctions

File mystats.m Functions mystats are


only accessible
from outside the file
mystats

mean Functions mean


and median are
only accessible
median from Inside the file

D.S. Aldar K.B.P.C.O.E.P Satara 170


subfunction
function[avg,med] = mystats(u)
n= length(u);
avg = mean(u,n);
med = median(u,n);
end;
function a = mean(v,n)
a = sum(v)/n;
end;
function m = median(v,n)
w = sort(v);
if rem(n,2) = = 1
m =w((n+1)/2;
else
m =(w(n/2)+w(n/2 + 1))/2;
end;
end; D.S. Aldar K.B.P.C.O.E.P Satara 171
Private Functions

• Private functions are functions that reside in


subdirectories with the special name private.
• A function that calls a private function must be
defined in an M-file that resides in the directory
immediately above that private subdirectory.
• A script that calls a private function must itself be
called from an M-file function that has access to the
private function according to the above rule.
• Primary functions and subfunctions can also be
implemented as private functions.
D.S. Aldar K.B.P.C.O.E.P Satara 172
Nested Functions
• one or more functions within another function can be defined
in MATLAB.
• Inner functions are said to be nested within the function that
contains them.
• You can also nest functions within other nested functions.
Multiply Nested Functions:

D.S. Aldar K.B.P.C.O.E.P Satara 173


Function Functions
EVAL – Evaluate the character string which is typed on command
prompt
eval(string)
FEVAL- Execute the specified function.
feval (fun, value)
Ex:
>> eval('sin(pi/4)')
ans =
0.7071
>> x=feval('sin',pi/4)
function hello(fun,x)
x=
y=feval(fun,x);
0.7071

>> hello('sin',pi/4)
D.S. Aldar K.B.P.C.O.E.P Satara 174
Function handles
INLINE - Construct INLINE object.
INLINE(EXPR) constructs an inline function object from the MATLAB expression
contained in the string EXPR.
Examples:
g = inline('t^2')
g = inline('sin(2*pi*f + theta)')

>> g = inline('t^2')
g=
Inline function:
g(t) = t^2
>> g(6)
ans =
36
D.S. Aldar K.B.P.C.O.E.P Satara 175
Function handles & Anonymous function

>> hum=inline('3*x.^2+2*x+4')
hum =
Inline function:
hum(x) = 3*x.^2+2*x+4

>> y=feval('sin',pi*(0:4)/4)
y=
0 0.7071 1.0000 0.7071 0.0000

>> y=feval(hum,[-1 0 1])


y=
5 4 9 D.S. Aldar K.B.P.C.O.E.P Satara 176
Anonymous function
Anonymous function introduced in MATLAB7 as a
replacement for inline function.

>> hum=@(x) 3*x.^2+2*x+4


hum =
@(x) 3*x.^2+2*x+4

>> y=feval(hum,[-1 0 1])


y=

5 4 9
D.S. Aldar K.B.P.C.O.E.P Satara 177
preparsed pseudocode file (P-file)

PCODE -Create pre-parsed pseudo-code file (P-file).

PCODE FUN parses the M-file FUN.M into the pre-


parsed pseudo-code file (P-file) FUN.P and puts it
into the current directory
>> pcode filename

D.S. Aldar K.B.P.C.O.E.P Satara 178


Errors and Debugging
•You will find that you will seldom get your scripts to run correctly the
first time.
• You will need to learn to identify and correct the errors, known in
computer jargon as bugs.

Syntax Errors:
The most common type of error is the syntax error, a typing error in a
Matlab command (for example, srqt instead of sqrt).

D.S. Aldar K.B.P.C.O.E.P Satara 179


Errors and Debugging
Run-time and Logic Errors

Run-time Errors:
These errors occur when your script is run on a particular set of data.
They typically occur when the result of some operation leads to NaN
(not a number),Inf (infinity), or an empty array .

Logic Errors:
These are errors in your programming logic, when your script executes
Properly, but does not produce the intended result. When this occurs,
you need to re-think the development and implementation of your
problem-solving algorithm.

D.S. Aldar K.B.P.C.O.E.P Satara 180


Errors and Debugging

The following are suggestions to help with the debugging


of Matlab scripts or M-files:

• Execute the script on a simple version of the problem, using test


data for which the results are known, to determine which displayed
results are incorrect.

• Remove semicolons from selected commands in the script so that


intermediate results are displayed.

• Add statements that display variables of interest within the script.

• Place the keyboard command at selected places in the script to give


temporary control to the keyboard. By doing so, the workspace can
be interrogated and values changed as necessary. Resume script
execution by issuing a return command at the keyboard prompt.
D.S. Aldar K.B.P.C.O.E.P Satara 181
Interactive Input
INPUT Prompt for user input.
R = INPUT('What is your name','s') gives the prompt in the
text string and waits for character string input.
Example:
R= input('Do you want more? Y/N [Y]: ', 's');
if isempty(reply)
reply = 'Y';
end;
ginput: Graphical input from mouse or cursor
[x,y] = ginput(n) or [x,y] = ginput

Examples:
Pick 10 two-dimensional points from the figure window.
[x,y] = ginput(10)
D.S. Aldar K.B.P.C.O.E.P Satara 182
Interactive Input

KEYBOARD : Invoke keyboard from M-file.


• KEYBOARD, when placed in an M-file, stops execution of
the file and gives control to the user's keyboard.
• The special status is indicated by a K appearing before the
prompt. Variables may be examined or changed - all
MATLAB commands are valid.
• The keyboard mode is terminated by executing the
command RETURN on the special prompt k>> (i.e. typing
the six letters R-E-T-U-R-N and pressing the return key).
Control returns to the invoking M-file.

D.S. Aldar K.B.P.C.O.E.P Satara 183


Interactive Input
Example:
clc;
clear;
a=eye(5);
for j=1:5
disp(j);
if j==3
keyboard;
p=m+j;
disp('hi this is p=');
disp(p);
end;
end;
D.S. Aldar K.B.P.C.O.E.P Satara 184
Interactive Input

menu: Generate menu of choices for user input


k = menu('mtitle','opt1','opt2',...,'optn')

Example:
k = menu('Choose a size','Large','Medium','small')
k=
3

i.e. you clicked on small

D.S. Aldar K.B.P.C.O.E.P Satara 185


Import Wizard
• Activate the import wizard by typing uiimport or by selecting import data option
on the MATLAB desktop file menu.
dsa.txt
1 2 3 4 5;
17 12 8 15 25;

dsa.xls
Sr.no data
1 65
2 56
3 65
4 35
5 64
6 94
7 46
8 45
9 24
10 45 D.S. Aldar K.B.P.C.O.E.P Satara 186
Import Wizard
>> xlsread('Book1.xls')
ans = >> textread('dsa.txt')
1 65 ans =
1 2 3 4 5
2 56 17 12 8 15 25
3 65
4 35
5 64
6 94
7 46
8 45
9 24
10 45
D.S. Aldar K.B.P.C.O.E.P Satara 187
The textread Function
• It is designed to read ASCII files that are formatted into columns of data
• Each column can be of a different type
• It is useful for importing tables of data printed out by other applications

• [a,b,c,…] = textread(filename,format,n)
– filename: a string that is the name of the file to be read
– format: a string containing the format primitives (just like in fprintf)
– n: number of lines to read (if not specified, the file is read until the
end)

D.S. Aldar K.B.P.C.O.E.P Satara 188


The textread Function

• Example: Assume that you have a file called phones.txt


Ingale Akman Prof 1538
Hameed Abdul AsstProf 3405
Mali Arun Prof 2249
Devi Rajan Prof 1625
Godbole Bhalchandra Prof 1208
Sangale Shivaji AsstProf 2613
Nanaware Jalindar AsstProf 1589
Shivdas Sunil AsstProf 1248
Tiple Hemant SrLecturer 4201
...

D.S. Aldar K.B.P.C.O.E.P Satara 189


The textread Function
[fname,lname,rank,phone] = textread( 'phones.txt', '%s %s %s %d' )

fname = lname = rank = phone =

'Ingale' 'Akman' 'Prof' 1538


'Hameed' 'Abdul' 'AsstProf' 3405
'Mali' 'Arun' 'Prof' 2249
'Devi' 'Rajan' 'Prof' 1625
'Godbole' 'Bhalchandra' 'Prof' 1208
'Sangale' 'Shivaji' 'AsstProf' 2613
'Nanaware' 'Jalindar' 'AsstProf' 1589
'Shivdas' 'Sunil' 'AsstProf' 1248
'Tiple' 'Hemant' 'SrLecturer' 4201

docuble array
cell array
cell array D.S. Aldar K.B.P.C.O.E.P Satara 190
The textread Function
• The textread function skips the columns that have an asterisk
(*) in the format descriptor

>> [fname, phone] = textread( 'phones.txt', '%s %*s %*s %d' )

fname = phone =

'Ingale' 1538
'Hameed' 3405
'Mali' 2249
'Devi' 1625
'Godbole' 1208
'Sangale' 2613
'Nanaware' 1589
'Shivdas' 1248
'Tiple' 4201
D.S. Aldar K.B.P.C.O.E.P Satara 191
The textread Function
• The load command (with ASCII option) assumes all of the
data is of a single type but textread is more flexible

• Example: Searching for telephone numbers


name = „mali‟;
for ii = 1:length(fname),
if ( strcmp( fname(ii), name ) ),
disp( phone(ii) );
end
end

D.S. Aldar K.B.P.C.O.E.P Satara 192


TIME
CPUTIME - Elapsed CPU time in seconds.
CPUTIME returns the CPU time in seconds that has been used
by the MATLAB process since MATLAB started.

For example:
t=cputime; your_operation; cputime-t
returns the cpu time used to run your_operation.

EXA: t = cputime; surf(peaks(40)); e = cputime-t

t = cputime;
g=magic(3);
surf(peaks(40));
e = cputime-t D.S. Aldar K.B.P.C.O.E.P Satara 193
TIME
TIC -Start a stopwatch timer.
TOC -Read the stopwatch timer.
TIC and TOC functions work together to measure elapsed
time.
TIC
operations
t =TOC

Exa:
Example: for n = 1:100
clc;clear; A = rand(n,n);
tic; b = rand(n,1);
x=0:10; tic
x = A\b;
plot(x,x);
t(n) = toc;
toc; end
t=toc; plot(t) 194
TIME
ETIME Elapsed time.
ETIME(T1,T0) returns the time in seconds that has elapsed between
vectors T1 and T0. The two vectors must be six elements long, in the
format returned by CLOCK:
T = [Year Month Day Hour Minute Second]
t0 = clock;
operation
etime(clock,t0)

Examples:
Calculate how long a 2048-point real FFT takes.
x = rand(2048,1);
t = clock; fft(x);
etime(clock,t)
D.S. Aldar K.B.P.C.O.E.P Satara 195
Sparse Matrices
SPARSE - Create sparse matrix.
S = SPARSE(X) converts a sparse or full matrix to sparse
form by squeezing out any zero elements.
>> a=eye(5) >> as=sparse(a)
a= as =
(1,1) 1
1 0 0 0 0
(2,2) 1
0 1 0 0 0 (3,3) 1
0 0 1 0 0 (4,4) 1
(5,5) 1
0 0 0 1 0
0 0 0 0 1
D.S. Aldar K.B.P.C.O.E.P Satara 196
Sparse Matrices
>> whos
Name Size Bytes Class
a 5x5 200 double array
as 5x5 84 double array (sparse)
Grand total is 30 elements using 284 bytes

SPEYE -Sparse identity matrix.


SPEYE(M,N) forms an M-by-N sparse matrix with 1's on
the main diagonal. SPEYE(N) abbreviates SPEYE(N,N).

D.S. Aldar K.B.P.C.O.E.P Satara 197


Sparse Matrices
FULL - Convert sparse matrix to full matrix.
A = FULL(X) converts a sparse matrix S to full storage organization. If X is a full
matrix, it is left unchanged.
>> a=speye(4)
a=
(1,1) 1
(2,2) 1 SPRAND - Sparse uniformly distributed random matrix.
(3,3) 1
R = SPRAND(S) has the same sparsity structure as S,
(4,4) 1
but uniformly distributed random entries.

>> b=full(a) SPRANDN Sparse normally distributed random matrix.


b= R = SPRANDN(S) has the same sparsity structure as S,
1 0 0 0 but normally distributed random entries.
0 1 0 0
0 0 1 0
0 0 0 1 D.S. Aldar K.B.P.C.O.E.P Satara 198
Sparse Matrices
>> A=[3*eye(3,3) ones(3,2)];
>> A=[3*eye(3,3) ones(3,2)]
>> b=[3;0;0]
>> k=sparse(A) >> c=[A,b];
k= >> k=sparse(c)
(1,1) 3 k=
(2,2) 3 (1,1) 3
(2,2) 3
(3,3) 3
(3,3) 3
(1,4) 1 (1,4) 1
(2,4) 1 (2,4) 1
(3,4) 1 (3,4) 1
(1,5) 1 (1,5) 1
(2,5) 1
(2,5) 1
(3,5) 1
(3,5) 1 (1,6) 3

D.S. Aldar K.B.P.C.O.E.P Satara 199


Sparse Matrices

D.S. Aldar K.B.P.C.O.E.P Satara 200


Sparse Matrices
>> load airfoil SPY : Visualize sparsity pattern.
>> A = sparse(i,j,1);
0

>> spy(A) 500

1000

1500

2000

2500

3000

3500

4000

0 500 1000 1500 2000 2500 3000 3500 4000


nz = 12289
D.S. Aldar K.B.P.C.O.E.P Satara 201
Descriptive Statistics

D.S. Aldar K.B.P.C.O.E.P Satara 202


Input/Output Functions
Save & load

• save filename var1 var2 …


– save homework.mat x y  binary
– save x.dat x –ascii  ascii
• load filename
– load filename.mat  binary
– load x.dat –ascii  ascii

D.S. Aldar K.B.P.C.O.E.P Satara 203


Input/Output Functions
Save & load

• save filename var1 var2 …


– save homework.mat x y  binary
– save x.dat x –ascii  ascii
• load filename
– load filename.mat  binary
– load x.dat –ascii  ascii
Input/Output Functions
File Processing
• File types:
– Binary files
• Data is stored in program readable format
• Processing is fast
– Text (ASCII) files
• Data is stored in human readable format
• Processing is slower
• Can be used to export/import data that can
be used in programs other than MATLAB
Input/Output Functions
Opening Files
• fid = fopen( filename, permission )
opens the file filename in the mode specified by
permission
– fid is the file id (a positive integer) that is assigned to
the file by MATLAB
– fid is used for all reading, writing and control
operations on that file
– file id 1 is the standard output device and file id 2 is the
standard error device
– fid will contain -1 if the file could not be opened
Input/Output Functions
Opening Files
• Permission can be:
– ‘r’ : open file for reading (default)
– ‘w’: open file, or create a new file, for writing; discard
existing contents, if any
– ‘a’: open file, or create a new file, for writing; append
data to the end of the file
– ‘r+’: open file for reading and writing
– ‘w+’: open file, or create a new file, for reading and
writing; discard existing contents, if any
– ‘a+’: open file, or create a new file, for reading and
writing; append data to the end of the file
• Add ‘t’ to the permission string for a text file
Input/Output Functions
Opening Files
• Examples:
– fid = fopen( ‘dsa.dat’, ‘r’ )
opens a binary file for input
– fid = fopen( ‘dsa.dat’, ‘wt’ )
opens a text file for output (if example.dat already
exists, it will be deleted)
– fid = fopen( ‘dsa.dat’, ‘at’ )
opens a text file for output (if example.dat already
exists, new data will be appended to the end)
Input/Output Functions
Opening Files
•Examples:

dsa.dat
0.00 1.00000000
0.10 1.10517092 >> fid = fopen( ‘dsa.dat’, ‘r’ )
0.20 1.22140276
0.30 1.34985881 >>d = fread(fid,'*char')'
0.40 1.49182470
0.50 1.64872127
0.60 1.82211880
0.70 2.01375271
0.80 2.22554093
0.90 2.45960311
1.00 2.71828183

D.S. Aldar K.B.P.C.O.E.P Satara 209


Input/Output Functions
Closing Files
• status = fclose( fid )
closes the file with file id fid
– If the closing operation is successful, status will
be 0
– If the closing operation is unsuccessful, status
will be -1
• status = fclose( ‘all’ )
closes all open files (except for standard output
and standard error)
Input/Output Functions
File Processing
Example 1
• The file alphabet.txt contains the 26 letters of the
English alphabet, all capitalized. Open the file for
read access with fopen, and read the first five
elements into output c. Because a precision has not
been specified, MATLAB uses the default precision of
uint8, and the output is numeric:
>>fid = fopen('alphabet.txt', 'r');
>>c = fread(fid, 5)'
>> c = 65 66 67 68 69
>> fclose(fid);
Input/Output Functions
File Processing
• This time, specify that you want each element
read as an unsigned 8-bit integer and output
as a character. (Using a precision of
'char=>char' or '*char' will produce the same
result):
>>fid = fopen('alphabet.txt', 'r');
>>c = fread(fid, 5, 'uint8=>char')‘
>>c = ABCDE
>>fclose(fid);
Input/Output Functions
File Processing
• When you leave out the optional count
argument, MATLAB reads the file to the end, A
through Z:
>>fid = fopen('alphabet.txt', 'r');
>>c = fread(fid, '*char')'
>> c =ABCDEFGHIJKLMNOPQRSTUVWXYZ
fclose(fid);
File Processing
• The fopen function positions the file pointer at the start
of the file. So the first fread in this example reads the first
five elements in the file, and then repositions the file
pointer at the beginning of the next element. For this
reason, the next fread picks up where the previous fread
left off, at the character F.
>>fid = fopen('alphabet.txt', 'r');
>>c1 = fread(fid, 5, '*char');
>>c2 = fread(fid, 8, '*char');
>>c3 = fread(fid, 5, '*char');
>>fclose(fid);
>>sprintf('%c', c1, ' * ', c2, ' * ', c3)
ans = ABCDE * FGHIJKLM * NOPQR
File Processing
Skip two elements between each read by specifying a skip argument
of 2:
>>fid = fopen('alphabet.txt', 'r');
>>c = fread(fid, '*char', 2); % Skip 2 bytes per read
>>fclose(fid);
>> sprintf('%c', c)
ans = ADGJMPSVY
File Processing
Example 2
• This command displays the complete M-file
containing this fread help entry:
• type fread.m To simulate this command using fread,
enter the following:
• fid = fopen('fread.m', 'r'); F = fread(fid, '*char')';
fclose(fid); In the example, the fread command
assumes the default size, 'inf', and precision '*char'
(the same as 'char=>char'). fread reads the entire
file. To display the result as readable text, the column
vector is transposed to a row vector.
File Processing
Example 3
• As another example,
• s = fread(fid, 120, '40*uchar=>uchar', 8); reads in 120 bytes in
blocks of 40, each separated by 8 bytes. Note that the class
type of s is 'uint8' since it is the appropriate class
corresponding to the destination format 'uchar'. Also, since 40
evenly divides 120, the last block read is a full block, which
means that a final skip is done before the command is
finished. If the last block read is not a full block, then fread
does not finish with a skip.
• See fopen for information about reading big and little-endian
files.
File Processing
Example 4
• Invoke the fopen function with just an fid input argument to obtain the machine format for
the file. You can see that this file was written in IEEE floating point with little-endian byte
ordering ('ieee-le') format:
• fid = fopen('A1.dat', 'r');
• [fname, mode, mformat] = fopen(fid);
• Mformat
• mformat = ieee-le
• Use the MATLAB format function (not related to the machine format type) to have MATLAB
display output using hexadecimal:
• format hex Now use the machineformat input with fread to read the data from the file using
the same format:
x = fread(fid, 6, 'uint64', 'ieee-le')
x = 4260800000002000
0000000000000000
4282000000180000
0000000000000000
42ca5e0000258000
42f0000464d45200
fclose(fid);
• Change the machine format to IEEE floating point with big-endian byte ordering ('ieee-be')
and verify that you get different results:
• fid = fopen('A1.dat', 'r');
• x = fread(fid, 6, 'uint64', 'ieee-be')
• x = 4370000008400000 0000000000000000 4308000200100000 0000000000000000
4352c0002f0d0000 43c022a6a3000000 fclose(fid);
File Processing
Example 5
• This example reads some Japanese text from a file that uses
the Shift-JIS character encoding scheme. It creates a string of
Unicode® characters, str, and displays the string. Note that the
computer must be configured to display Japanese (e.g., a
Japanese machine running the Windows operating system) for
the output of disp(str) to be correct.
fid = fopen('japan.txt', 'r', 'n', 'Shift_JIS');
str = fread(fid, '*char')';
fclose(fid);
disp(str);
Writing Formatted Text Data
FPRINTF -Write formatted data to file.
fprintf(format,data) – is used to convert numerical result to ASCII format.
FORMAT STRING RESULTS
%d Display value as an integer
%f Display value in floating format
%e Display value in exponential format
%g Display value in either exponential or floating point format,
Whichever is shortest
\n Skip to new line
>> fprintf('the value of pi is %6.2f \n',pi) % floating point in six character wide the
value of pi is 3.14
>> fprintf('the value of pi is %8.2f \n',pi) % eight character wide with line feed
the value of pi is 3.14
Writing Formatted Text Data
• count = fprintf(fid,format,val1,val2,…)
writes formatted text data in a user-specified format
– fid: file id (if fid is missing, data is written to the
standard output device (command window)
– format: same as what we have been using
(combination of format specifiers that start with %)
– count: number of characters written
Writing Formatted Text Data
• Make sure there is a one-to-one correspondence between
format specifiers and types of data in variables
• Format strings are scanned from left to right
• Program goes back to the beginning of the format string if
there are still values to write (format string is recycled)
• If you want to print the actual % character, you can use
%% in the format string
Writing Formatted Text Data
• Conversion specifications begin with the % character
and contain these optional and required elements:
• Flags (optional)
• Width and precision fields (optional)
• A subtype specifier (optional)
• Conversion character (required)

•You specify these elements in the following order:


Writing Formatted Text Data

Flags
You can control the alignment of the output using any of these optional
flags.
Writing Formatted Text Data
Conversion Characters
Conversion characters specify the notation of the output.
Writing Formatted Text Data
Escape Characters
This table lists the escape character sequences you use to specify
nonprinting characters in a format specification.
Writing Formatted Text Data

Example 1:
Create a text file called exp.txt containing a short table of the exponential
function. (On Windows platforms, it is recommended that you use fopen with
the mode set to 'wt' to open a text file for writing.)

x = 0:.1:1;
y = [x; exp(x)];
fid = fopen('exp.txt', 'wt');
fprintf(fid, '%6.2f %12.8f\n', y);
fclose(fid)
Example 2:
>> fprintf( ...
'A unit circle has circumference %g radians.\n', 2*pi)
A unit circle has circumference 6.28319 radians.
Writing Formatted Text Data

Example 3:

Use fprintf to display a hyperlink on the screen.

>> site = '"http://www.mathworks.com"';


title = 'The MathWorks Web Site';
fprintf(['<a href = ' site '>' title '</a>'])
The MathWorks Web Site>>
Reading Formatted Text Data
• [array,count] = fscanf(fid,format,size)
reads formatted text data in a user-specified format
– fid: file id
– format: same as format in fprintf
– size: same as size in fread
– array: array that receives the data
– count: number of elements read

• line = fgetl( fid )


reads the next line excluding the end-of-line characters from a file as a
character string
– line: character array that receives the data
– line is set to -1 if fgetl encounters the end of a file
Reading Formatted Text Data

Example:

fid = fopen('exp.txt', 'r');


a = fscanf(fid, '%g %g', [2 inf]) % It has two rows now.
a = a';
fclose(fid)
MATLAB EDIT WINDOW

Cell Evaluate ,increment,


decrement toolbar

D.S. Aldar K.B.P.C.O.E.P Satara 231


M-Lint Code Analyzer
• The M-Lint code analyzer checks your code for
problems and recommends modifications to maximize
performance and maintainability
• Ways to Use M-Lint:
– Run a report for an existing M-file or group of M-files. i.e.
from an M-file in the Editor/Debugger, select Tools > M-
Lint > Show M-Lint Report
– Make any changes to your file based on the M-Lint
messages in the report. After making changes, you must
save the file and rerun the report to see if your changes
addressed the issues noted in M-Lint messages.
– Continuously check code in the Editor/Debugger while
you work.
– View M-Lint messages and make changes to your file
based on the messages.
D.S. Aldar K.B.P.C.O.E.P Satara 232
M-Lint Code Check Report
• MLINT : Display inconsistencies and
suspicious constructs in M-files.
– MLINT(FILENAME) :displays M-Lint information
about FILENAME.
• MATLAB Desktop > Current directory toolbar
>M-Lint Code Check Report

D.S. Aldar K.B.P.C.O.E.P Satara 233


Directory Reports in Current Directory
Browser
• Accessing and Using Directory Reports
• TODO/FIXME Report
• Help Report
• Contents Report
• Dependency Report
• Coverage Report

D.S. Aldar K.B.P.C.O.E.P Satara 234


Directory Reports in Current Directory
Browser
• Access directory reports from the MATLAB Current Directory
browser.
• To display the Current Directory browser, select : Desktop >
Current Directory

235
TODO/FIXME Report
• The TODO/FIXME Report shows M-files that
contain text strings you included as notes to
yourself, such as TODO.
• Use this report to easily identify M-files that
still require work or some other actions

D.S. Aldar K.B.P.C.O.E.P Satara 236


TODO/FIXME Report

237
Help Report
• The Help Report presents a summary view of
the help component of your M-files.
• In MATLAB, the M-file help component is all
contiguous non-executable lines (comment
lines and blank lines), starting with the second
line of a function M-file or the first line of a
script M-file.

D.S. Aldar K.B.P.C.O.E.P Satara 238


239
Contents Report
• The Contents Report displays information
about the integrity of the Contents.m file for
the directory.
• A Contents.m file includes the filename and a
brief description of each M-file in the
directory. When you type help followed by the
directory name, such as help mydemos,
MATLAB displays the information in the
mydemos/Contents.m file.

D.S. Aldar K.B.P.C.O.E.P Satara 240


Contents Report

241
Dependency Report
• The Dependency Report shows dependencies
among M-files in a directory.
• This helps you determine all the M-files you need
to provide when you tell someone to run a
particular M-file.
• If you do not provide all the dependent M-files
along with the M-file you want them to run, they
will not be able run the file.
• The report does not list as dependencies the M-
files in the toolbox/matlab directory because
every MATLAB user already has those files.

D.S. Aldar K.B.P.C.O.E.P Satara 242


Dependency Report

243
Coverage Report
• Run the Coverage Report after you run the
Profiler to identify how much of a file ran
when it was profiled.
• For example, when you have an if statement
in your code, that section might not run
during profiling, depending on conditions.

D.S. Aldar K.B.P.C.O.E.P Satara 244


Profiling for Improving Performance
What Is Profiling?
 Profiling is a way to measure where a program spends its time.
 Using the MATLAB Profiler, you can identify which functions in
your code consume the most time.
 You can then determine why you are calling them and look for
ways to minimize their use.
 It is often helpful to decide whether the number of times a
particular function is called is reasonable.
 Profiling helps to uncover performance problems that you can
solve by
 Avoiding unnecessary computation, which can arise from oversight
 Changing your algorithm to avoid costly functions
 Avoiding recomputation by storing results for future use
D.S. Aldar K.B.P.C.O.E.P Satara 245
Profiling for Improving Performance
Opening the Profiler
 Opening the Profiler You can use any of the following
methods to open the Profiler:
 Select Desktop > Profiler from the MATLAB desktop.
 Click the Profiler button in the MATLAB desktop toolbar.
 With a file open in the MATLAB Editor/Debugger, select
Tools > Open Profiler.
 Select one or more statements in the Command History
window,right-click to view the context menu, and choose
Profile Code.
 Enter the following function in the Command Window:
>> profile viewer or >> profile report
246
D.S. Aldar K.B.P.C.O.E.P Satara
Profiling for Improving Performance
profile on - Turn the profiler on
profile off - Turn it back off
profile clear - Clear profiler statistics
profile report - View the results from the profiler

>> profile on, profile clear


>> example1(5000);
>> profile report

D.S. Aldar K.B.P.C.O.E.P Satara 247


Profiling for Improving Performance
Running the Profiler
• The following illustration summarizes the steps for profiling.

248
Profile Summary Report

249
MATLAB Notebook
• The MATLAB Notebook allows you to access MATLAB’s
numeric computation and visualization software from
within a word processing environment (Microsoft Word).
• Using the Notebook, you can create a document that
contains text, MATLAB commands, and the output from
MATLAB commands.
• You can think of this document as a record of an
interactive MATLAB session annotated with text or as a
document embedded with live MATLAB commands and
output.

D.S. Aldar K.B.P.C.O.E.P Satara 250


MATLAB Notebook
• The Notebook is useful for creating electronic
or printed:
– Documents
– Records of MATLAB sessions
– Class notes
– Textbooks and handbooks
– Technical reports
• To start notebook type
>> notebook
D.S. Aldar K.B.P.C.O.E.P Satara 251
252
D.S. Aldar K.B.P.C.O.E.P Satara

You might also like