SlideShare ist ein Scribd-Unternehmen logo
1 von 87
INTRODUCTION TO MATLAB
By
Chesti Altaff HussainMATLAB BASICS1
MATLAB (matrix laboratory) is a numerical computing environment
and fourth generation programming language.
Developed by Math Works.
MATLAB allows matrix manipulations, plotting of functions and data,
implementation of algorithms creation of user interfaces and interfacing
with programs written in other languages, including C, C++,JAVA and
Fortron.
MATLAB® is a high-level language and interactive environment for
numerical computation, visualization, and programming.
Using MATLAB, you can analyze data, develop algorithms, and create
models and applications.
The language, tools, and built-in math functions enable you to explore
multiple approaches and reach a solution faster than with spreadsheets
or traditional programming languages, such as C/C++ or Java.
MATLAB BASICS2
You can use MATLAB for a range of applications, including signal
processing and communications, image and video processing, control
systems, test and measurement, computational finance, and
computational biology.
More than a million engineers and scientists in industry and academia
use MATLAB, the language of technical computing.
Advantages of MATLAB
 Ease of use
 Platform independence
 Predefined functions
 Plotting
Disadvantages of MATLAB
 Can be slow
 Commercial software
MATLAB BASICS3
Matlab Screen
Command Window
type commands
Current Directory
View folders and m-files
Workspace
View program variables
Double click on a variable
to see it in the Array Editor
Command History
view past commands
save a whole session
using diary
MATLAB BASICS4
MATLAB BASICS6
Array: A collection of data values organized into
rows and columns, and known by a single name.
Row 1
Row 2
Row 3
Row 4
Col 1 Col 2 Col 3 Col 4 Col 5
arr(3,2)
MATLAB BASICS
MATLAB Editor Window
MATLAB BASICS
6
MATLAB Help Window (Very Powerful)
MATLAB BASICS7
MATLAB BASICS
8
Keyword Search of Help Entries
>> lookfor who
newton.m: % inputs: 'x' is the number whose
square root we seek
testNewton.m: % inputs: 'x' is the number
whose square root we seek
WHO List current variables.
WHOS List current variables, long form.
TIMESTWO S-function whose output is two times
its input.
>> whos
Name Size Bytes Class Attributes
ans 1x1 8 double
fid 1x1 8 double
i 1x1 8 double
MATLAB BASICS
Arrays
The fundamental unit of data in MATLAB
Scalars are also treated as arrays by
MATLAB (1 row and 1 column).
Row and column indices of an array start
from 1.
Arrays can be classified as vectors and
matrices.
MATLAB BASICS
9
MATLAB BASICS
Vector: Array with one dimension
Matrix: Array with more than one
dimension
Size of an array is specified by the number
of rows and the number of columns, with
the number of rows mentioned first (For
example: n x m array).
 Total number of elements in an array is the
product of the number of rows and the
number of columns.
MATLAB BASICS
10
MATLAB BASICS
MATLAB BASICS
11
1 2
3 4
5 6
a= 3x2 matrix  6 elements
b=[1 2 3 4] 1x4 array  4 elements, row vector
c=
1
3
5
3x1 array  3 elements, column vector
a(2,1)=3 b(3)=3 c(2)=3
Row # Column #
MATLAB BASICS
12
32
54
7
6
1
10
8 9
11 12
4
7
1
10
2
5
MATLAB BASICS
8
11
Multidimensional Arrays
• A two dimensional array with m rows and n
columns will occupy mxn successive locations in
the computer’s memory. MATLAB always
allocates array elements in column major
order.
a= [1 2 3; 4 5 6; 7 8 9; 10 11 12];
a(5) = a(1,2) = 2
• A 2x3x2 array of three dimensions
c(:, :, 1) = [1 2 3; 4 5 6 ];
c(:, :, 2) = [7 8 9; 10 11 12];
MATLAB BASICS
Variables
 Variable names must begin with a letter,
followed by any combination of letters, numbers
and the underscore (_) character.
 The MATLAB language is Case Sensitive. NAME,
name and Name are all different variables.
 Give meaningful (descriptive and easy-to-remember)
names for the variables. Never define a variable with the
same name as a MATLAB function or command.
MATLAB BASICS
13
Variables and Workspace
• Information is stored in
variables.
>> a = 10
a =
10
>>
Real numbers
Matlab is case sensitive (a  A)
MATLAB BASICS
15
• Information is stored in
variables.
» a = 3+2i
a =
3.0000 + 2.0000i
Imaginary numbers
MATLAB BASICS
16
Variables and Workspace
• Variables are stored in the
workspace
» who
Your variables are:
a
MATLAB BASICS
17
» whos
Name Size Bytes Class
a 1x1 8 double array
Grand total is 1 elements using 8 bytes
Name of the variable
Size of the variable
Type of variable (String, double)
• Variables are stored in the
workspace
MATLAB BASICS
18
Variables and Workspace
» clear a
» who
»
• Variables are stored in the
workspace
Variable list
MATLAB BASICS
19
Variables and Workspace
» a = 8;
» save tmp a
»
• Variables can be saved in files.
Semicolon suppresses output
File name Variable list (separate with spaces)
MATLAB BASICS
20
Variables and Workspace
» a = 8;
» save tmp a
» clear
» who
» load tmp
» who
Your variables are:
a
• Variables can be saved in files.
MATLAB BASICS
21
MATLAB BASICS
Common types of MATLAB variables
 double: 64-bit double-precision floating-point numbers
They can hold real, imaginary or complex numbers in the
range from ±10-308 to ±10308 with 15 or 16 decimal digits.
>> var = 1 + i ;
 char: 16-bit values, each representing a single character
The char arrays are used to hold character strings.
>> comment = ‘This is a character string’ ;
The type of data assigned to a variable determines the type
of variable that is created.
MATLAB BASICS
22
MATLAB BASICS23
Initializing Variables in Assignment
Statements
An assignment statement has the general form
var = expression
Examples:
>> var = 40 * i; >> a2 = [0 1+8];
>> var2 = var / 5; >> b2 = [a2(2) 7 a];
>> array = [1 2 3 4]; >> c2(2,3) = 5;
>> x = 1; y = 2; >> d2 = [1 2];
>> a = [3.4]; >> d2(4) = 4;
>> b = [1.0 2.0 3.0 4.0];
>> c = [1.0; 2.0; 3.0];
>> d = [1, 2, 3; 4, 5, 6]; ‘;’ semicolon
suppresses the
>> e = [1, 2, 3
4, 5, 6]; automatic echoing of values
but It slows down the execution.
MATLAB BASICS
27
Initializing with Keyboard Input
• The input function displays a prompt string in
the Command Window and then waits for the
user to respond.
my_val = input( ‘Enter an input value: ’ );
in1 = input( ‘Enter data: ’ );
in2 = input( ‘Enter data: ’ ,`s`);
MATLAB BASICS
MATLAB BASICS
28
Subarrays
• The end function: When used in an array
subscript, it returns the highest value taken on
by that subscript.
arr3 = [1 2 3 4 5 6 7 8];
arr3(5:end) is the array [5 6 7 8]
arr4 = [1 2 3 4; 5 6 7 8; 9 10 11 12];
arr4(2:end, 2:end)
MATLAB BASICS
MATLAB BASICS
29
Subarrays
• Assigning a Scalar to a Subarray: A scalar value
on the right-hand side of an assignment
statement is copied into every element specified
on the left-hand side.
>> arr4 = [1 2 3 4; 5 6 7 8; 9 10 11 12];
>> arr4(1:2, 1:2) = 1
arr4 =
1 1 3 4
1 1 7 8
9 10 11 12
MATLAB BASICS
MATLAB BASICS
30
Special Values
• MATLAB includes a number of predefined special values.
These values can be used at any time without initializing
them.
• These predefined values are stored in ordinary variables.
They can be overwritten or modified by a user.
• If a new value is assigned to one of these variables, then
that new value will replace the default one in all later
calculations.
>> circ1 = 2 * pi * 10;
>> pi = 3;
>> circ2 = 2 * pi * 10;
Never change the values of predefined variables.
MATLAB BASICS
MATLAB BASICS
31
Special Values
• pi:  value up to 15 significant digits
• i, j: sqrt(-1)
• Inf: infinity (such as division by 0)
• NaN: Not-a-Number (division of zero by zero)
• clock: current date and time in the form of a 6-
element row vector containing the year,
month, day, hour, minute, and second
• date: current date as a string such as 16-Feb-
2004
• eps: epsilon is the smallest difference between
two numbers
• ans: stores the result of an expression
MATLAB BASICS32
>> prompt
. . . continue statement on next line
, separate statements and data
% start comment which ends at end of line
; (1) suppress output
(2) used as a row separator in a
matrix
: specify range
MATLAB BASICS
33
Changing the data format
>> value = 12.345678901234567;
format short  12.3457
format long  12.34567890123457
format short e  1.2346e+001
format long e 
1.234567890123457e+001
format short g  12.346
format long g 
12.3456789012346
format rat  1000/81
MATLAB BASICS
MATLAB BASICS
The disp( array ) function
>> disp( 'Hello' )
Hello
>> disp(5)
5
>> disp( [ 'Bilkent ' 'University' ] )
Bilkent University
>> name = 'Alper';
>> disp( [ 'Hello ' name ] )
Hello Alper
MATLAB BASICS34
MATLAB BASICS
The num2str() and int2str()
functions
>> d = [ num2str(16) '-Feb-'
num2str(2004) ];
>> disp(d)
16-Feb-2004
>> x = 23.11;
>> disp( [ 'answer = ' num2str(x) ] )
answer = 23.11
>> disp( [ 'answer = ' int2str(x) ] )
answer = 23
MATLAB BASICS35
MATLAB BASICS
The fprintf( format, data ) function
– %d integer
– %f floating point format
– %e exponential format
– %g either floating point or
exponential format, whichever is
shorter
– n new line character
– t tab character
MATLAB BASICS36
>> fprintf( 'Result is %d', 3 )
Result is 3
>> fprintf( 'Area of a circle with radius %d is %f',
3, pi*3^2 )
Area of a circle with radius 3 is 28.274334
>> x = 5;
>> fprintf( 'x = %3d', x )
x = 5
>> x = pi;
>> fprintf( 'x = %0.2f', x )
x = 3.14
>> fprintf( 'x = %6.2f', x )
x = 3.14
>> fprintf( 'x = %dny = %dn', 3, 13 )
x = 3
y = 13
MATLAB BASICS37
MATLAB BASICS
• variable_name = expression;
– addition a + b  a + b
– subtraction a - b  a - b
– multiplication a x b  a * b
– division a / b  a / b
– exponent ab  a ^ b
MATLAB BASICS38
Hierarchy of operations
• x = 3 * 2 + 6 / 2
• Processing order of operations is
important
– parentheses (starting from the innermost)
– exponentials (from left to right)
– multiplications and divisions (from left to
right)
– additions and subtractions (from left to
right)
>> x = 3 * 2 + 6 / 2
x =
9
MATLAB BASICS39
Built-in MATLAB Functions
• result = function_name( input );
– abs, sign
– log, log10, log2
– exp
– sqrt
– sin, cos, tan
– asin, acos, atan
– max, min
– round, floor, ceil, fix
– mod, rem
• help elfun  help for elementary math
functions
MATLAB BASICS40
• Information is stored in
variables.
» a = [1 2 3; 4 5 6]
a =
1 2 3
4 5 6
Matrices
MATLAB BASICS
41
• Information is stored in
variables.
» a = [1 2 3
4 5 6]
a =
1 2 3
4 5 6
Matrices
[Enter]
MATLAB BASICS
42
Matrix Manipulations
• Matrix creation
» var = zeros(3,2)
var =
0 0
0 0
0 0
Rows
Columns
MATLAB BASICS
43
Matrix Manipulations
• Matrix creation
» var = ones (3,2)
var =
1 1
1 1
1 1
Rows Columns
MATLAB BASICS
44
• Matrix creation
» tmp = eye(3)
tmp =
1 0 0
0 1 0
0 0 1
MATLAB BASICS
45
• Matrix creation
» x = [1 2 3];
» tmp = diag(x)
tmp =
1 0 0
0 2 0
0 0 3
tmp = diag([1 2 3])
MATLAB BASICS
46
• Matrix creation
» rand(3)
ans =
0.9501 0.4860 0.4565
0.2311 0.8913 0.0185
0.6068 0.7621 0.8214
MATLAB BASICS
47
• Matrix creation
» tmp = [zeros(2,2),ones(2),diag([2 5])]
tmp =
0 0 1 1 2 0
0 0 1 1 0 5
» matrix = [1 , 2 , 3 ; 4 , 5 ,6 ; 7 , 8 , 9]
matrix =
1 2 3
4 5 6
7 8 9
MATLAB BASICS
48
Matrix Manipulations
MATLAB BASICS
49
• Matrix creation
a = [1:12]
a =
1 2 3 4 5 6 7 8 9 10 11 12
Start End
Matrix Manipulations
MATLAB BASICS
50
• Matrix creation
» a = [ 1 : 0.1 : 1.5 ]
a =
1.0000 1.1000 1.2000 1.3000 1.4000 1.5000
Start
End
Step
Basic functions
 Arithmetic functions
 (+) Addition
 (-) Negation and subtraction
 (*) Multiplication
 (/) Right division
 () Left division
 (^) Exponentiation
MATLAB BASICS
51
MATLAB Relational Operators
 MATLAB supports six relational operators.
Less Than <
Less Than or Equal <=
Greater Than >
Greater Than or Equal >=
Equal To ==
Not Equal To ~=
MATLAB BASICS
52
MATLAB Logical Operators
MATLAB supports three logical operators.
not ~ % highest precedence
and & % equal precedence with or
or | % equal precedence with and
MATLAB BASICS
53
MATLAB Logical Functions
 MATLAB also supports some logical functions.
xor (exclusive or) Ex: xor (a, b)
Where a and b are logical expressions. The xor operator
evaluates to true if and only if one expression is true
and the other is false. True is returned as 1, false as 0.
any (x) returns 1 if any element of x is nonzero
all (x) returns 1 if all elements of x are nonzero
isnan (x) returns 1 at each NaN in x
isinf (x) returns 1 at each infinity in x
finite (x) returns 1 at each finite value in x
MATLAB BASICS
54
• Arithmetic functions
» 10/2
ans =
5
» 102
ans =
0.2000
MATLAB BASICS
55
Basic
functions
• Arithmetic functions
» a = [1 5; 6 9];
» b = [5 8; 2 6];
» c = a*b
c =
15 38
48 102
MATLAB BASICS
56
Basic
functions
• Element-by-element
operations
» a = [1 5; 6 9];
» b = [5 8; 2 6];
» c = a .*b
c =
5 40
12 54
MATLAB BASICS
57
• Element-by-element
operations
c = a*a
c = a(1,1) * a(1,1) ...
» a = [1 5; 6 9];
» c = a^2
c =
31 50
60 111
» c = a.^2
c =
1 25
36 81
MATLAB BASICS
58
• Elementary mathematical
functions
abs Absolute value
sqrt Square root
real Real part
imag Imaginary part
exp Exponential base e
log Natural logarithm
sin, cos, tan Trigonometric functions
MATLAB BASICS
59
• Elementary mathematical functions
sin, cos, tan Trigonometric functions
round Round to the nearest integer
fix Round toward zero
floor Round toward -Inf
ceil Round toward +Inf
MATLAB BASICS
60
• Elementary mathematical
functions
» floor(3.4)
ans =
3
» ceil(3.4)
ans =
4
MATLAB BASICS
61
Basic functions
• Matrix functions
a’ Transpose
inv Inverse of a matrix
det Matrix determinant
eig Matrix eigenvalues -
eigenvectors
size Matrix Size
MATLAB BASICS
62
Basic
functions
• Matrix functions
» a = [3 8; 8 3];
» inv(a)
ans =
-0.0545 0.1455
0.1455 -0.0545
» size(a)
ans =
2 2
MATLAB BASICS
63
Extracting a Sub-Matrix
 A portion of a matrix can be extracted and
stored in a smaller matrix by specifying the
names of both matrices and the rows and
columns to extract. The syntax is:
sub_matrix = matrix ( r1 : r2 , c1 : c2 )
;
where r1 and r2 specify the beginning and
ending rows and c1 and c2 specify the
beginning and ending columns to be extracted
to make the new matrix.
MATLAB BASICS
64
Matrix Manipulations
• Matrix subscripts
» tmp = rand(3)
tmp =
0.4447 0.9218 0.4057
0.6154 0.7382 0.9355
0.7919 0.1763 0.9169
» tmp(2,3)
ans =
0.9355
MATLAB BASICS
65
Matrix Manipulations
• Matrix subscripts
» tmp(1,2) = 0
tmp =
0.4447 0 0.4057
0.6154 0.7382 0.9355
0.7919 0.1763 0.9169
MATLAB BASICS
66
Matrix Manipulations
• Matrix subscripts
» tmp = rand(3)
tmp =
0.4660 0.5252 0.8381
0.4186 0.2026 0.0196
0.8462 0.6721 0.6813
» tmp(:,1)
ans =
0.4660
0.4186
0.8462
MATLAB BASICS
67
MATLAB BASICS68
Flow Control Constructs
 Logic Control:
 IF / ELSEIF / ELSE
 SWITCH / CASE / OTHERWISE
 Iterative Loops:
 FOR
 WHILE
Control Structures
If Statement Syntax
if (Condition_1)
Matlab Commands
elseif (Condition_2)
Matlab Commands
elseif (Condition_3)
Matlab Commands
else
Matlab Commands
end
MATLAB BASICS69
Some Dummy Examples
if ((a>3) & (b==5))
Some Matlab Commands;
end
if (a<3)
Some Matlab Commands;
elseif (b~=5)
Some Matlab Commands;
end
if (a<3)
Some Matlab Commands;
else
Some Matlab Commands;
end
If statement
 EX (1):
If a<0
disp (‘a is negative’);
end
 EX (2):
If x<0
error (‘x is negative; sqrt(x) is imaginary’);
else
r=sqrt(x);
end
 EX(3):
If x>0
disp(‘x is positive’);
elseif x<0
disp (‘x is negative’);
else
disp (‘x is exactly zero’);
end
MATLAB BASICS70
MATLAB BASICS71
Switch, Case, and Otherwise
switch input_num
case -1
input_str = 'minus one';
case 0
input_str = 'zero';
case 1
input_str = 'plus one';
case {-10,10}
input_str = '+/- ten';
otherwise
input_str = 'other value';
end
Switch statement syntax:
Switch expression
case value1
Matlab Commands
case value2
Matlab Commands
.
.
.
otherwise,
Matlab Commands
end
Difference between if, and switch
More efficient than elseif statements
Only the first matching case is
executed
MATLAB BASICS72
Control Structures
For loop syntax
for i=Index_Array
Matlab Commands
end
MATLAB BASICS73
Some Dummy Examples
for i=1:100
Some Matlab Commands;
end
for j=1:3:200
Some Matlab Commands;
end
for m=13:-0.2:-21
Some Matlab Commands;
end
for k=[0.1 0.3 -13 12 7 -9.3]
Some Matlab Commands;
end
For loop
 Example: Sum of elements in a vector
X=1:5; %create a row vector
Sumx=0; %initialize the sum
For k=1:length(x)
sumx=sumx+x(k);
end
 Example: A loop with non-integer increments
For x=0:pi/15:pi
fprintf(‘%8.2f %8.5fn’,x,sin(x));
end
MATLAB BASICS74
Control Structures
 While Loop Syntax
while (condition)
Matlab Commands
end
MATLAB BASICS75
Dummy Example
while ((a>3) & (b==5))
Some Matlab Commands;
end
While loop
 EX:
>>Counter=5;
>>factorial=1;
While(counter>0)
factorial=factorial*counter %multiply
counter=counter-1 %decrement
end
 EX: we can approximate the smallest nonzero float
point no
>>x=1;
while x>0
xmin=x;
x=x/2;
end
>>xmin
MATLAB BASICS76
Types of errors in MATLAB
programs
• Syntax errors
– Check spelling and punctuation
• Run-time errors
– Check input data
– Can remove “;” or add “disp” statements
• Logical errors
– Use shorter statements
– Check typos
– Check units
– Ask assistants, instructor, …
MATLAB BASICS78
M-Files
• Create additional functions
– function
• Automatic tasks
MATLAB BASICS
79
M-Files
• The edit window
» edit
MATLAB BASICS
80
Graphics in MATLAB
MATLAB BASICS
81
0 500 1000 1500 2000 2500 3000
-3
-2
-1
0
1
2
3
4
• 2D Plots
• 3D Plots
Graphics in MATLAB
• 2D Plotting commands
plot General 2D plots
xlabel, ylabel Axis labels
title Title of the figure
text Text in the figure
gtext Text in the figure (Mouse
input)
MATLAB BASICS
82
Matlab Graphs
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
xlabel('x = 0:2pi')
ylabel('Sine of x')
title('Plot of the
Sine Function')
MATLAB BASICS83
Graphics in MATLAB
• 2D Plots
» x = [0.1:0.1:20]; y = [x.^3];
» plot (x,y)
» title ('This is the title')
» xlabel ('Label on X axis')
» ylabel ('Label on Y axis')
» grid
MATLAB BASICS
84
Graphics in MATLAB
MATLAB BASICS
85
• Subplot command
» subplot(211)
» plot(x,y)
» subplot(212)
» plot(y,x)
Graphics in MATLAB
• 2D Plotting (logarithmic plots)
» semilogx (x)
» semilogy (x)
» loglog (x)
MATLAB BASICS
86
Multiple Graphs
t = 0:pi/100:2*pi;
y1=sin(t);
y2=sin(t+pi/2);
plot(t,y1,t,y2)
grid on
MATLAB BASICS88
Graphics in MATLAB
• Additional example
» plot(x,y,’g’)
» hold on
» plot(x,2*y,’r’)
»
MATLAB BASICS
89
Graphics in MATLAB
• 3D Plotting
MATLAB BASICS
91
Graphics in MATLAB
3D Plot
MATLAB BASICS 92
>> z=0:0.1:10*pi;
>> x = exp(-z/20).*cos(z);
>> y = exp(-z/20).*sin(z);
>> plot3(x,y,z, 'LineWidth' ,2)
Graphics in MATLAB
• 3D Plot
surf Surface plot generation
mesh Mesh plot generation
contour Contour plot generation
MATLAB BASICS
93
Graphics in MATLAB
• 3D Plot
» z = peaks(30);
» surf(peaks)
» mesh(peaks)
» contour(z)
MATLAB BASICS
94

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
MATLAB - Arrays and Matrices
MATLAB - Arrays and MatricesMATLAB - Arrays and Matrices
MATLAB - Arrays and Matrices
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
 
Matlab intro
Matlab introMatlab intro
Matlab intro
 
Matlab Tutorial.ppt
Matlab Tutorial.pptMatlab Tutorial.ppt
Matlab Tutorial.ppt
 
What is matlab
What is matlabWhat is matlab
What is matlab
 
Introduction to Matlab
Introduction to MatlabIntroduction to Matlab
Introduction to Matlab
 
Matlab for beginners, Introduction, signal processing
Matlab for beginners, Introduction, signal processingMatlab for beginners, Introduction, signal processing
Matlab for beginners, Introduction, signal processing
 
Matlab Functions
Matlab FunctionsMatlab Functions
Matlab Functions
 
MATLAB Programming
MATLAB Programming MATLAB Programming
MATLAB Programming
 
Matlab ppt
Matlab pptMatlab ppt
Matlab ppt
 
Matlab (Presentation on MATLAB)
Matlab (Presentation on MATLAB)Matlab (Presentation on MATLAB)
Matlab (Presentation on MATLAB)
 
Matlab-free course by Mohd Esa
Matlab-free course by Mohd EsaMatlab-free course by Mohd Esa
Matlab-free course by Mohd Esa
 
Matlab introduction
Matlab introductionMatlab introduction
Matlab introduction
 
Matlab matrices and arrays
Matlab matrices and arraysMatlab matrices and arrays
Matlab matrices and arrays
 
Basic operators in matlab
Basic operators in matlabBasic operators in matlab
Basic operators in matlab
 
Matlab introduction
Matlab introductionMatlab introduction
Matlab introduction
 
An Introduction to MATLAB for beginners
An Introduction to MATLAB for beginnersAn Introduction to MATLAB for beginners
An Introduction to MATLAB for beginners
 
Matlab basic and image
Matlab basic and imageMatlab basic and image
Matlab basic and image
 

Ähnlich wie Matlab ppt

matlab-130408153714-phpapp02_lab123.ppsx
matlab-130408153714-phpapp02_lab123.ppsxmatlab-130408153714-phpapp02_lab123.ppsx
matlab-130408153714-phpapp02_lab123.ppsx
lekhacce
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
Kurmendra Singh
 

Ähnlich wie Matlab ppt (20)

Introduction to Matlab - Basic Functions
Introduction to Matlab - Basic FunctionsIntroduction to Matlab - Basic Functions
Introduction to Matlab - Basic Functions
 
matlab-130408153714-phpapp02_lab123.ppsx
matlab-130408153714-phpapp02_lab123.ppsxmatlab-130408153714-phpapp02_lab123.ppsx
matlab-130408153714-phpapp02_lab123.ppsx
 
A complete introduction on matlab and matlab's projects
A complete introduction on matlab and matlab's projectsA complete introduction on matlab and matlab's projects
A complete introduction on matlab and matlab's projects
 
Matlab
MatlabMatlab
Matlab
 
Introduction to Matlab.ppt
Introduction to Matlab.pptIntroduction to Matlab.ppt
Introduction to Matlab.ppt
 
MatlabIntro (1).ppt
MatlabIntro (1).pptMatlabIntro (1).ppt
MatlabIntro (1).ppt
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
 
Matlab1
Matlab1Matlab1
Matlab1
 
Matlab introduction
Matlab introductionMatlab introduction
Matlab introduction
 
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulinkMATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
 
From zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyondFrom zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyond
 
Matlab-1.pptx
Matlab-1.pptxMatlab-1.pptx
Matlab-1.pptx
 
Matlab Overviiew
Matlab OverviiewMatlab Overviiew
Matlab Overviiew
 
1.1Introduction to matlab.pptx
1.1Introduction to matlab.pptx1.1Introduction to matlab.pptx
1.1Introduction to matlab.pptx
 
MATLAB-Introd.ppt
MATLAB-Introd.pptMATLAB-Introd.ppt
MATLAB-Introd.ppt
 
Mat lab workshop
Mat lab workshopMat lab workshop
Mat lab workshop
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
Introduction to Matlab.pdf
Introduction to Matlab.pdfIntroduction to Matlab.pdf
Introduction to Matlab.pdf
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
 

Kürzlich hochgeladen

VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
MsecMca
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
Epec Engineered Technologies
 

Kürzlich hochgeladen (20)

Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Unit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfUnit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdf
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 

Matlab ppt

  • 1. INTRODUCTION TO MATLAB By Chesti Altaff HussainMATLAB BASICS1
  • 2. MATLAB (matrix laboratory) is a numerical computing environment and fourth generation programming language. Developed by Math Works. MATLAB allows matrix manipulations, plotting of functions and data, implementation of algorithms creation of user interfaces and interfacing with programs written in other languages, including C, C++,JAVA and Fortron. MATLAB® is a high-level language and interactive environment for numerical computation, visualization, and programming. Using MATLAB, you can analyze data, develop algorithms, and create models and applications. The language, tools, and built-in math functions enable you to explore multiple approaches and reach a solution faster than with spreadsheets or traditional programming languages, such as C/C++ or Java. MATLAB BASICS2
  • 3. You can use MATLAB for a range of applications, including signal processing and communications, image and video processing, control systems, test and measurement, computational finance, and computational biology. More than a million engineers and scientists in industry and academia use MATLAB, the language of technical computing. Advantages of MATLAB  Ease of use  Platform independence  Predefined functions  Plotting Disadvantages of MATLAB  Can be slow  Commercial software MATLAB BASICS3
  • 4. Matlab Screen Command Window type commands Current Directory View folders and m-files Workspace View program variables Double click on a variable to see it in the Array Editor Command History view past commands save a whole session using diary MATLAB BASICS4
  • 5. MATLAB BASICS6 Array: A collection of data values organized into rows and columns, and known by a single name. Row 1 Row 2 Row 3 Row 4 Col 1 Col 2 Col 3 Col 4 Col 5 arr(3,2) MATLAB BASICS
  • 7. MATLAB Help Window (Very Powerful) MATLAB BASICS7
  • 8. MATLAB BASICS 8 Keyword Search of Help Entries >> lookfor who newton.m: % inputs: 'x' is the number whose square root we seek testNewton.m: % inputs: 'x' is the number whose square root we seek WHO List current variables. WHOS List current variables, long form. TIMESTWO S-function whose output is two times its input. >> whos Name Size Bytes Class Attributes ans 1x1 8 double fid 1x1 8 double i 1x1 8 double
  • 9. MATLAB BASICS Arrays The fundamental unit of data in MATLAB Scalars are also treated as arrays by MATLAB (1 row and 1 column). Row and column indices of an array start from 1. Arrays can be classified as vectors and matrices. MATLAB BASICS 9
  • 10. MATLAB BASICS Vector: Array with one dimension Matrix: Array with more than one dimension Size of an array is specified by the number of rows and the number of columns, with the number of rows mentioned first (For example: n x m array).  Total number of elements in an array is the product of the number of rows and the number of columns. MATLAB BASICS 10
  • 11. MATLAB BASICS MATLAB BASICS 11 1 2 3 4 5 6 a= 3x2 matrix  6 elements b=[1 2 3 4] 1x4 array  4 elements, row vector c= 1 3 5 3x1 array  3 elements, column vector a(2,1)=3 b(3)=3 c(2)=3 Row # Column #
  • 12. MATLAB BASICS 12 32 54 7 6 1 10 8 9 11 12 4 7 1 10 2 5 MATLAB BASICS 8 11 Multidimensional Arrays • A two dimensional array with m rows and n columns will occupy mxn successive locations in the computer’s memory. MATLAB always allocates array elements in column major order. a= [1 2 3; 4 5 6; 7 8 9; 10 11 12]; a(5) = a(1,2) = 2 • A 2x3x2 array of three dimensions c(:, :, 1) = [1 2 3; 4 5 6 ]; c(:, :, 2) = [7 8 9; 10 11 12];
  • 13. MATLAB BASICS Variables  Variable names must begin with a letter, followed by any combination of letters, numbers and the underscore (_) character.  The MATLAB language is Case Sensitive. NAME, name and Name are all different variables.  Give meaningful (descriptive and easy-to-remember) names for the variables. Never define a variable with the same name as a MATLAB function or command. MATLAB BASICS 13
  • 14. Variables and Workspace • Information is stored in variables. >> a = 10 a = 10 >> Real numbers Matlab is case sensitive (a  A) MATLAB BASICS 15
  • 15. • Information is stored in variables. » a = 3+2i a = 3.0000 + 2.0000i Imaginary numbers MATLAB BASICS 16
  • 16. Variables and Workspace • Variables are stored in the workspace » who Your variables are: a MATLAB BASICS 17
  • 17. » whos Name Size Bytes Class a 1x1 8 double array Grand total is 1 elements using 8 bytes Name of the variable Size of the variable Type of variable (String, double) • Variables are stored in the workspace MATLAB BASICS 18
  • 18. Variables and Workspace » clear a » who » • Variables are stored in the workspace Variable list MATLAB BASICS 19
  • 19. Variables and Workspace » a = 8; » save tmp a » • Variables can be saved in files. Semicolon suppresses output File name Variable list (separate with spaces) MATLAB BASICS 20
  • 20. Variables and Workspace » a = 8; » save tmp a » clear » who » load tmp » who Your variables are: a • Variables can be saved in files. MATLAB BASICS 21
  • 21. MATLAB BASICS Common types of MATLAB variables  double: 64-bit double-precision floating-point numbers They can hold real, imaginary or complex numbers in the range from ±10-308 to ±10308 with 15 or 16 decimal digits. >> var = 1 + i ;  char: 16-bit values, each representing a single character The char arrays are used to hold character strings. >> comment = ‘This is a character string’ ; The type of data assigned to a variable determines the type of variable that is created. MATLAB BASICS 22
  • 22. MATLAB BASICS23 Initializing Variables in Assignment Statements An assignment statement has the general form var = expression Examples: >> var = 40 * i; >> a2 = [0 1+8]; >> var2 = var / 5; >> b2 = [a2(2) 7 a]; >> array = [1 2 3 4]; >> c2(2,3) = 5; >> x = 1; y = 2; >> d2 = [1 2]; >> a = [3.4]; >> d2(4) = 4; >> b = [1.0 2.0 3.0 4.0]; >> c = [1.0; 2.0; 3.0]; >> d = [1, 2, 3; 4, 5, 6]; ‘;’ semicolon suppresses the >> e = [1, 2, 3 4, 5, 6]; automatic echoing of values but It slows down the execution.
  • 23. MATLAB BASICS 27 Initializing with Keyboard Input • The input function displays a prompt string in the Command Window and then waits for the user to respond. my_val = input( ‘Enter an input value: ’ ); in1 = input( ‘Enter data: ’ ); in2 = input( ‘Enter data: ’ ,`s`); MATLAB BASICS
  • 24. MATLAB BASICS 28 Subarrays • The end function: When used in an array subscript, it returns the highest value taken on by that subscript. arr3 = [1 2 3 4 5 6 7 8]; arr3(5:end) is the array [5 6 7 8] arr4 = [1 2 3 4; 5 6 7 8; 9 10 11 12]; arr4(2:end, 2:end) MATLAB BASICS
  • 25. MATLAB BASICS 29 Subarrays • Assigning a Scalar to a Subarray: A scalar value on the right-hand side of an assignment statement is copied into every element specified on the left-hand side. >> arr4 = [1 2 3 4; 5 6 7 8; 9 10 11 12]; >> arr4(1:2, 1:2) = 1 arr4 = 1 1 3 4 1 1 7 8 9 10 11 12 MATLAB BASICS
  • 26. MATLAB BASICS 30 Special Values • MATLAB includes a number of predefined special values. These values can be used at any time without initializing them. • These predefined values are stored in ordinary variables. They can be overwritten or modified by a user. • If a new value is assigned to one of these variables, then that new value will replace the default one in all later calculations. >> circ1 = 2 * pi * 10; >> pi = 3; >> circ2 = 2 * pi * 10; Never change the values of predefined variables. MATLAB BASICS
  • 27. MATLAB BASICS 31 Special Values • pi:  value up to 15 significant digits • i, j: sqrt(-1) • Inf: infinity (such as division by 0) • NaN: Not-a-Number (division of zero by zero) • clock: current date and time in the form of a 6- element row vector containing the year, month, day, hour, minute, and second • date: current date as a string such as 16-Feb- 2004 • eps: epsilon is the smallest difference between two numbers • ans: stores the result of an expression
  • 28. MATLAB BASICS32 >> prompt . . . continue statement on next line , separate statements and data % start comment which ends at end of line ; (1) suppress output (2) used as a row separator in a matrix : specify range
  • 29. MATLAB BASICS 33 Changing the data format >> value = 12.345678901234567; format short  12.3457 format long  12.34567890123457 format short e  1.2346e+001 format long e  1.234567890123457e+001 format short g  12.346 format long g  12.3456789012346 format rat  1000/81 MATLAB BASICS
  • 30. MATLAB BASICS The disp( array ) function >> disp( 'Hello' ) Hello >> disp(5) 5 >> disp( [ 'Bilkent ' 'University' ] ) Bilkent University >> name = 'Alper'; >> disp( [ 'Hello ' name ] ) Hello Alper MATLAB BASICS34
  • 31. MATLAB BASICS The num2str() and int2str() functions >> d = [ num2str(16) '-Feb-' num2str(2004) ]; >> disp(d) 16-Feb-2004 >> x = 23.11; >> disp( [ 'answer = ' num2str(x) ] ) answer = 23.11 >> disp( [ 'answer = ' int2str(x) ] ) answer = 23 MATLAB BASICS35
  • 32. MATLAB BASICS The fprintf( format, data ) function – %d integer – %f floating point format – %e exponential format – %g either floating point or exponential format, whichever is shorter – n new line character – t tab character MATLAB BASICS36
  • 33. >> fprintf( 'Result is %d', 3 ) Result is 3 >> fprintf( 'Area of a circle with radius %d is %f', 3, pi*3^2 ) Area of a circle with radius 3 is 28.274334 >> x = 5; >> fprintf( 'x = %3d', x ) x = 5 >> x = pi; >> fprintf( 'x = %0.2f', x ) x = 3.14 >> fprintf( 'x = %6.2f', x ) x = 3.14 >> fprintf( 'x = %dny = %dn', 3, 13 ) x = 3 y = 13 MATLAB BASICS37
  • 34. MATLAB BASICS • variable_name = expression; – addition a + b  a + b – subtraction a - b  a - b – multiplication a x b  a * b – division a / b  a / b – exponent ab  a ^ b MATLAB BASICS38
  • 35. Hierarchy of operations • x = 3 * 2 + 6 / 2 • Processing order of operations is important – parentheses (starting from the innermost) – exponentials (from left to right) – multiplications and divisions (from left to right) – additions and subtractions (from left to right) >> x = 3 * 2 + 6 / 2 x = 9 MATLAB BASICS39
  • 36. Built-in MATLAB Functions • result = function_name( input ); – abs, sign – log, log10, log2 – exp – sqrt – sin, cos, tan – asin, acos, atan – max, min – round, floor, ceil, fix – mod, rem • help elfun  help for elementary math functions MATLAB BASICS40
  • 37. • Information is stored in variables. » a = [1 2 3; 4 5 6] a = 1 2 3 4 5 6 Matrices MATLAB BASICS 41
  • 38. • Information is stored in variables. » a = [1 2 3 4 5 6] a = 1 2 3 4 5 6 Matrices [Enter] MATLAB BASICS 42
  • 39. Matrix Manipulations • Matrix creation » var = zeros(3,2) var = 0 0 0 0 0 0 Rows Columns MATLAB BASICS 43
  • 40. Matrix Manipulations • Matrix creation » var = ones (3,2) var = 1 1 1 1 1 1 Rows Columns MATLAB BASICS 44
  • 41. • Matrix creation » tmp = eye(3) tmp = 1 0 0 0 1 0 0 0 1 MATLAB BASICS 45
  • 42. • Matrix creation » x = [1 2 3]; » tmp = diag(x) tmp = 1 0 0 0 2 0 0 0 3 tmp = diag([1 2 3]) MATLAB BASICS 46
  • 43. • Matrix creation » rand(3) ans = 0.9501 0.4860 0.4565 0.2311 0.8913 0.0185 0.6068 0.7621 0.8214 MATLAB BASICS 47
  • 44. • Matrix creation » tmp = [zeros(2,2),ones(2),diag([2 5])] tmp = 0 0 1 1 2 0 0 0 1 1 0 5 » matrix = [1 , 2 , 3 ; 4 , 5 ,6 ; 7 , 8 , 9] matrix = 1 2 3 4 5 6 7 8 9 MATLAB BASICS 48
  • 45. Matrix Manipulations MATLAB BASICS 49 • Matrix creation a = [1:12] a = 1 2 3 4 5 6 7 8 9 10 11 12 Start End
  • 46. Matrix Manipulations MATLAB BASICS 50 • Matrix creation » a = [ 1 : 0.1 : 1.5 ] a = 1.0000 1.1000 1.2000 1.3000 1.4000 1.5000 Start End Step
  • 47. Basic functions  Arithmetic functions  (+) Addition  (-) Negation and subtraction  (*) Multiplication  (/) Right division  () Left division  (^) Exponentiation MATLAB BASICS 51
  • 48. MATLAB Relational Operators  MATLAB supports six relational operators. Less Than < Less Than or Equal <= Greater Than > Greater Than or Equal >= Equal To == Not Equal To ~= MATLAB BASICS 52
  • 49. MATLAB Logical Operators MATLAB supports three logical operators. not ~ % highest precedence and & % equal precedence with or or | % equal precedence with and MATLAB BASICS 53
  • 50. MATLAB Logical Functions  MATLAB also supports some logical functions. xor (exclusive or) Ex: xor (a, b) Where a and b are logical expressions. The xor operator evaluates to true if and only if one expression is true and the other is false. True is returned as 1, false as 0. any (x) returns 1 if any element of x is nonzero all (x) returns 1 if all elements of x are nonzero isnan (x) returns 1 at each NaN in x isinf (x) returns 1 at each infinity in x finite (x) returns 1 at each finite value in x MATLAB BASICS 54
  • 51. • Arithmetic functions » 10/2 ans = 5 » 102 ans = 0.2000 MATLAB BASICS 55
  • 52. Basic functions • Arithmetic functions » a = [1 5; 6 9]; » b = [5 8; 2 6]; » c = a*b c = 15 38 48 102 MATLAB BASICS 56
  • 53. Basic functions • Element-by-element operations » a = [1 5; 6 9]; » b = [5 8; 2 6]; » c = a .*b c = 5 40 12 54 MATLAB BASICS 57
  • 54. • Element-by-element operations c = a*a c = a(1,1) * a(1,1) ... » a = [1 5; 6 9]; » c = a^2 c = 31 50 60 111 » c = a.^2 c = 1 25 36 81 MATLAB BASICS 58
  • 55. • Elementary mathematical functions abs Absolute value sqrt Square root real Real part imag Imaginary part exp Exponential base e log Natural logarithm sin, cos, tan Trigonometric functions MATLAB BASICS 59
  • 56. • Elementary mathematical functions sin, cos, tan Trigonometric functions round Round to the nearest integer fix Round toward zero floor Round toward -Inf ceil Round toward +Inf MATLAB BASICS 60
  • 57. • Elementary mathematical functions » floor(3.4) ans = 3 » ceil(3.4) ans = 4 MATLAB BASICS 61
  • 58. Basic functions • Matrix functions a’ Transpose inv Inverse of a matrix det Matrix determinant eig Matrix eigenvalues - eigenvectors size Matrix Size MATLAB BASICS 62
  • 59. Basic functions • Matrix functions » a = [3 8; 8 3]; » inv(a) ans = -0.0545 0.1455 0.1455 -0.0545 » size(a) ans = 2 2 MATLAB BASICS 63
  • 60. Extracting a Sub-Matrix  A portion of a matrix can be extracted and stored in a smaller matrix by specifying the names of both matrices and the rows and columns to extract. The syntax is: sub_matrix = matrix ( r1 : r2 , c1 : c2 ) ; where r1 and r2 specify the beginning and ending rows and c1 and c2 specify the beginning and ending columns to be extracted to make the new matrix. MATLAB BASICS 64
  • 61. Matrix Manipulations • Matrix subscripts » tmp = rand(3) tmp = 0.4447 0.9218 0.4057 0.6154 0.7382 0.9355 0.7919 0.1763 0.9169 » tmp(2,3) ans = 0.9355 MATLAB BASICS 65
  • 62. Matrix Manipulations • Matrix subscripts » tmp(1,2) = 0 tmp = 0.4447 0 0.4057 0.6154 0.7382 0.9355 0.7919 0.1763 0.9169 MATLAB BASICS 66
  • 63. Matrix Manipulations • Matrix subscripts » tmp = rand(3) tmp = 0.4660 0.5252 0.8381 0.4186 0.2026 0.0196 0.8462 0.6721 0.6813 » tmp(:,1) ans = 0.4660 0.4186 0.8462 MATLAB BASICS 67
  • 64. MATLAB BASICS68 Flow Control Constructs  Logic Control:  IF / ELSEIF / ELSE  SWITCH / CASE / OTHERWISE  Iterative Loops:  FOR  WHILE
  • 65. Control Structures If Statement Syntax if (Condition_1) Matlab Commands elseif (Condition_2) Matlab Commands elseif (Condition_3) Matlab Commands else Matlab Commands end MATLAB BASICS69 Some Dummy Examples if ((a>3) & (b==5)) Some Matlab Commands; end if (a<3) Some Matlab Commands; elseif (b~=5) Some Matlab Commands; end if (a<3) Some Matlab Commands; else Some Matlab Commands; end
  • 66. If statement  EX (1): If a<0 disp (‘a is negative’); end  EX (2): If x<0 error (‘x is negative; sqrt(x) is imaginary’); else r=sqrt(x); end  EX(3): If x>0 disp(‘x is positive’); elseif x<0 disp (‘x is negative’); else disp (‘x is exactly zero’); end MATLAB BASICS70
  • 67. MATLAB BASICS71 Switch, Case, and Otherwise switch input_num case -1 input_str = 'minus one'; case 0 input_str = 'zero'; case 1 input_str = 'plus one'; case {-10,10} input_str = '+/- ten'; otherwise input_str = 'other value'; end Switch statement syntax: Switch expression case value1 Matlab Commands case value2 Matlab Commands . . . otherwise, Matlab Commands end
  • 68. Difference between if, and switch More efficient than elseif statements Only the first matching case is executed MATLAB BASICS72
  • 69. Control Structures For loop syntax for i=Index_Array Matlab Commands end MATLAB BASICS73 Some Dummy Examples for i=1:100 Some Matlab Commands; end for j=1:3:200 Some Matlab Commands; end for m=13:-0.2:-21 Some Matlab Commands; end for k=[0.1 0.3 -13 12 7 -9.3] Some Matlab Commands; end
  • 70. For loop  Example: Sum of elements in a vector X=1:5; %create a row vector Sumx=0; %initialize the sum For k=1:length(x) sumx=sumx+x(k); end  Example: A loop with non-integer increments For x=0:pi/15:pi fprintf(‘%8.2f %8.5fn’,x,sin(x)); end MATLAB BASICS74
  • 71. Control Structures  While Loop Syntax while (condition) Matlab Commands end MATLAB BASICS75 Dummy Example while ((a>3) & (b==5)) Some Matlab Commands; end
  • 72. While loop  EX: >>Counter=5; >>factorial=1; While(counter>0) factorial=factorial*counter %multiply counter=counter-1 %decrement end  EX: we can approximate the smallest nonzero float point no >>x=1; while x>0 xmin=x; x=x/2; end >>xmin MATLAB BASICS76
  • 73. Types of errors in MATLAB programs • Syntax errors – Check spelling and punctuation • Run-time errors – Check input data – Can remove “;” or add “disp” statements • Logical errors – Use shorter statements – Check typos – Check units – Ask assistants, instructor, … MATLAB BASICS78
  • 74. M-Files • Create additional functions – function • Automatic tasks MATLAB BASICS 79
  • 75. M-Files • The edit window » edit MATLAB BASICS 80
  • 76. Graphics in MATLAB MATLAB BASICS 81 0 500 1000 1500 2000 2500 3000 -3 -2 -1 0 1 2 3 4 • 2D Plots • 3D Plots
  • 77. Graphics in MATLAB • 2D Plotting commands plot General 2D plots xlabel, ylabel Axis labels title Title of the figure text Text in the figure gtext Text in the figure (Mouse input) MATLAB BASICS 82
  • 78. Matlab Graphs x = 0:pi/100:2*pi; y = sin(x); plot(x,y) xlabel('x = 0:2pi') ylabel('Sine of x') title('Plot of the Sine Function') MATLAB BASICS83
  • 79. Graphics in MATLAB • 2D Plots » x = [0.1:0.1:20]; y = [x.^3]; » plot (x,y) » title ('This is the title') » xlabel ('Label on X axis') » ylabel ('Label on Y axis') » grid MATLAB BASICS 84
  • 80. Graphics in MATLAB MATLAB BASICS 85 • Subplot command » subplot(211) » plot(x,y) » subplot(212) » plot(y,x)
  • 81. Graphics in MATLAB • 2D Plotting (logarithmic plots) » semilogx (x) » semilogy (x) » loglog (x) MATLAB BASICS 86
  • 82. Multiple Graphs t = 0:pi/100:2*pi; y1=sin(t); y2=sin(t+pi/2); plot(t,y1,t,y2) grid on MATLAB BASICS88
  • 83. Graphics in MATLAB • Additional example » plot(x,y,’g’) » hold on » plot(x,2*y,’r’) » MATLAB BASICS 89
  • 84. Graphics in MATLAB • 3D Plotting MATLAB BASICS 91
  • 85. Graphics in MATLAB 3D Plot MATLAB BASICS 92 >> z=0:0.1:10*pi; >> x = exp(-z/20).*cos(z); >> y = exp(-z/20).*sin(z); >> plot3(x,y,z, 'LineWidth' ,2)
  • 86. Graphics in MATLAB • 3D Plot surf Surface plot generation mesh Mesh plot generation contour Contour plot generation MATLAB BASICS 93
  • 87. Graphics in MATLAB • 3D Plot » z = peaks(30); » surf(peaks) » mesh(peaks) » contour(z) MATLAB BASICS 94