Matlab Introduction
Matlab Introduction
MATLAB
By
Mr. Rahul Kumar Gupta
M.Tech. (ECE-VLSI), IIT Dhanbad
B.Tech. (ECE), DTU, Delhi
Assistant Professor - EEE , Lingaya's Vidyapeeth, Faridabad, Haryana
Contact No.:+91-8802286651
What is MATLAB?
Stands for Matrix Laboratory.
Intro MATLAB
The Advantages of MATLAB
High Level
Languages such as
C, Pascal etc.
Assembly
Application of MATLAB
Math and computation
Algorithm development
Editor Window
• write and save program Current Folder
• View folders
and m-files
Command History
Workspace • view past commands
• View program variables • save a whole session
Command Window
• Type commands/program • Double click on a variable using diary
• Display output(s) to see it in the Variable Editor
MATLAB Variable names
– Variable names are case sensitive.
– Variable names can contain up to 63 characters
– Variable names must start with a letter and can be
followed by letters, digits and underscores.
Variables and Arrays
• MATLAB treats all variables as matrices. For our purposes a
matrix can be thought of as an array, in fact, that is how it is
stored.
• Vectors are special forms of matrices and contain only one
row OR one column.
• Scalars are matrices with only one row AND one column
1 2 3
A 4 5 6 A B ?
7 8 9
4 3
B
A* B ?
1 2
1 2 3
A 4 5 6 A3 X 3 B2 X 2
Error using +
Matrix dimensions must agree.
7 8 9 3 X 3
4 3
B A3 X 3 * B2 X 2 Error using *
Inner matrix dimensions must
1 2 2X 2 agree.
1 2 3 1 2 3
A 4 5 6 A B ? A .* B ? 4 5 6
7 8 9 7 8 9
1 1 1
B 1 1 1 A* B ?
1 1 1
1 2 3 2 3 4
A 4 5 6 A B
5 6 7
7 8 9 3 X 3 8 9 10
1 1 1 6 6 6
B 1 1 1 A* B 15 15 15
1 1 1 3 X 3 24 24 24
1 2 3
A 4 5 6
7 8 9
Long Array, Matrix
Generating Vectors from functions
• zeros(M,N) MxN matrix of zeros x = zeros(1,3)
x =
0 0 0
>> x = 0:pi/100:2*pi;
>> y = sin(x);
>> plot(x,y);
Titles and Labels
• MATLAB has commands which will let you add titles and
labels and others in order to make your figures more
readable.
>> xlabel(‘Radian’);
>> ylabel(‘Amplitude’);
>> title(‘Plot of sin(x) vs x’);
>> grid on;
• The current limits of this plot can be determined from
the basic axis function. So, in order to modify the x-axis
within [0 2π], you need to run this function:
>> x = linspace(0,2*pi);
>> subplot(2,2,1);
>> plot(x,sin(x));
>>
>> subplot(2,2,2)
>> plot(x,sin(2*x));
>>
>> subplot(2,2,3)
>> plot(x,sin(3*x));
>>
>> subplot(2,2,4)
>> plot(x,sin(4*x));
Multiple plots
>> x = linspace(0,2*pi);
>> y1 = sin(x);
>> y1 = cos(x);
>> y1 = tan(x);
>> plot(x,y1,x);
>> axis([0 2*pi -1 1]);
The hold Function
>> x = -pi:pi/20:pi;
>> y1 = sin(x);
>> y2 = cos(x);
>> plot(x,y1,'b-');
>> hold on;
>> plot(x,y2,'g--');
>> hold off;
>>
legend('sin(x)','cos(x)');
Three-Dimensional Surface Mesh Plots
• The first step in displaying a function of two variables, z = f(x,y), is to generate X
and Y matrices consisting of repeated rows and columns,
• Then use these matrices to evaluate and graph the function.
• Meshgrid function transforms the domain specified by two-vectors, x and y, into
matrices X and Y.
t = 0:pi/10:2*pi;
[x,y,z] = cylinder(4*cos(t));
subplot(2,2,1)
mesh(x)
subplot(2,2,2); mesh(y)
subplot(2,2,3); mesh(z)
subplot(2,2,4); mesh(x,y,z)
Controlling Axes
axis([xmin xmax ymin ymax])
axis square %makes the entire x-axes and y-axes the same length
axis equal % makes the individual tick mark increments on the x-
and y-axes the same length.
axis auto % returns the axis scaling to its default, automatic mode
axis on % turns on axis labeling and tick marks
axis off %turns off axis labeling and tick marks.
grid off %turns the grid lines off and grid on % turns them back
on again.
xlabel, ylabel,and zlabel % add x, y, and z axis labels
title % adds a title at the top of the figure
text % inserts text anywhere in the figure
e.g. t= –pi:pi/100:pi;
y = sin(t);
plot(t, y)
axis([–pi pi –1 1])
xlabel('–\pi \leq {\itt} \leq \pi')
ylabel('sin(t)')
title('Graph of the sine function')
text(1,–1/3,'\it{Note the odd symmetry.}')
Flow Control
• if
• switch
• for
• while
• break
Operators (relational, logical)
Control Structures
Some Dummy Examples
• If Statement Syntax
if ((a>3) & (b==5))
Some Matlab Commands;
if (Condition_1) end
Matlab Commands
if (a<3)
elseif (Condition_2) Some Matlab Commands;
Matlab Commands elseif (b~=5)
Some Matlab Commands;
elseif (Condition_3) end
Matlab Commands
if (a<3)
else Some Matlab Commands;
Matlab Commands else
end Some Matlab Commands;
end
• e.g.Given the following bus fare schedule:
• Regular fare Rs 10
• Children under 5 free
• Youth fare (ages 5-17)Rs. 5
• Senior fare (age 65+) Rs.5
– Goal: write a piece of code that determines a
passenger's fare
Matlab Script
%suppose age contains the passenger's age
fare = 10;
if age < 5
fare = 0;
disp('Under 5, free')
end
if (age >= 5 & age <= 17) || age >= 65
fare = 5;
disp('Discount fare')
end
‘switch’ statement
• switch Switch among several Example :
cases based on expression
x = 2;
The general form of the switch y = 3;
statement is: switch x
switch switch_expr case x==y
case case_expr1 disp('x and y are equal');
…
case case_expr2
case x>y
… disp('x is greater than y');
otherwise otherwise
…
end disp('x is less than y');
end
‘for’ loop
• for Repeat statements a Some Dummy Examples
specific number of times
for i=1:100
Some Matlab Commands;
The general form of a for end
printf(‘%d\n’,x);
end
Example 2: Sum of squares of odd numbers from 1 to 20
SumSq = 0;
for n = 1 : 2: 20
SumSq = SumSq + n^2;
end
SumSq
‘while’ loop
Dummy Example
while (condition)
Matlab Commands while ((a>3) & (b==5))
Some Matlab Commands;
end end
Examples
Example 1:
x = 1;
while x
disp(‘Infinite Loop: Please
press ctrl+C’)
end
Example 2: Sum of squares of even numbers from 1 to 20
SumSq = 0;
n = 2;
while n <= 20
SumSq = SumSq + n^2;
n = n+2
end
SumSq
Examples
e.g. Fibonacci numbers are 1, 1, 2, 3, 5, 8, …
• Goal: write a piece of Matlab code to find the first N=10
Fibonacci numbers.
N = 10;
fib = [1 1];
for k = 3 : N
fib(k) = fib(k-1) + fib(k-2);
end
disp(['The first ', num2str(N), ' Fibonacci numbers
are: '])
disp(fib)
‘break’ statement
• break terminates the execution of for and while loops
• In nested loops, break terminates from the innermost loop only
Example:
y = 3;
for x = 1:10
printf(‘%5d’,x);
if (x>y)
break;
end
end
1234
Efficient Programming in MATLAB
Avoid using nested loops as far as possible
In most cases, one can replace nested loops with efficient
matrix manipulation.
Pre-allocate your arrays when possible
MATLAB comes with a huge library of in-built functions, use
them when necessary
Avoid using your own functions, MATLAB’s functions are more
likely to be efficient than yours.
More examples
• Find the number of positive numbers in a vector
x = input( 'Enter a vector: ' );
count = 0;
for ii = 1:length(x),
if ( x(ii) > 0 ),
count = count + 1;
end
end
fprintf('Number of positive numbers is %d\n',
count);
• Find the index of the largest number in a vector
x = input( 'Enter a vector: ' );
max_value = x(1);
max_index = 1;
for ii = 2:length(x),
if ( x(ii) > max_value ),
max_value = x(ii);
max_index = ii;
end
end
fprintf( 'Max value is %d\n', max_value );
fprintf( 'Its index is %d\n', max_index );
Character Strings
The file is saved with the function name and the usual
MATLAB script file extension, ".m".