MATLAB Applications
MATLAB Applications
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..
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
C-kernel Simulink
m-files
5
The MathWorks Product Suite
Stateflow Coder
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.
Example:
>> load mtlb;
>> wavplay(mtlb,Fs);
>>save matlab;
>> wavemenu
… and import file to wavemenu
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.
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 ] ;
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.
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
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
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
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
>> 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 -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.
>> 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
>> 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.
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 = '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].
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):
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
104
Cartesian Coordinate System Conversion
• cart2sph:Transform Cartesian coordinates to
spherical
– Syntax
[THETA,PHI,R] = cart2sph(X,Y,Z)
109
D.S. Aldar K.B.P.C.O.E.P Satara
EUCLIDEAN NORM
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
f(x)/g(x)= 1.5x-.5833
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
c=
7.3409 -4.8409 1.6818
Res =
10 0
i.e. voltage = 10 X current
>> size(t)
ans =
1 12
>> whos
Name Size Bytes Class
time
>> 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 =
>> 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'
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.
Student(1) Student(2)
Somesh Sansita Name
Name
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
• 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
>>x=3.0;
>>y=x^2;
>>y
y =
9.0
>>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
Ex:
function f=myfunction(x,y)
f=x+y;
• save it in myfunction.m
• call it with y=myfunction(x,y)
Exa:
function [ radius, theta] = myfunc( x, y)
>> hello
??? Error using ==> hello
Not enough input arguments.
>> hello(2,3,5)
??? Error using ==> hello
Too many input arguments.
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
>> 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
5 4 9
D.S. Aldar K.B.P.C.O.E.P Satara 177
preparsed pseudocode file (P-file)
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).
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.
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
Example:
k = menu('Choose a size','Large','Medium','small')
k=
3
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)
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 =
'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
For example:
t=cputime; your_operation; cputime-t
returns the cpu time used to run your_operation.
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
1000
1500
2000
2500
3000
3500
4000
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
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:
Example:
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
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.
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.
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.
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.