LAB 01 Intro To Matlab
LAB 01 Intro To Matlab
INTRODUCTION TO MATLAB
LAB# 01
Introduction to Matlab
• What is Matlab?
– Matlab is a commercial “MATrix LABoratory” package by
• Command Window
– type commands
Workspace
– view program variables
– clear to clear
– double click on a variable to see it in the Array Editor
• Command History
– view past commands
– save a whole session using diary
Variables
• Active Variables:
– Who
• Removing Variables
– Clear x
– Clear
• Saving and Restoring Variables
– Save filename
– Load filename
Variable Arithmetic
• Operator precedence
– 2 + 3 *4 ^ 2
• Double Precision Arithmetic
– Normally the results will be displayed in a shorter form.
• a = sqrt( 2 ) >> a = 1.4142
– Format long
• b = sqrt ( 2 ) >> b = 1.41421356……….
– Format short
• Command Line Editing
– The arrow keys allow “ command line editing”
Built in Mathematical Functions
• The matrix element located in the i-th row and j-th column
of A is referred to in the usual way:
– >> A (1 , 2), A ( 2 , 3)
• Matrices can be easily modified:
– A ( 2 , 3 ) = 10;
• Building Matrices from a Block:
– Large matrices can be assembled from smaller matrix blocks i.e.
• C = [A;10 11 12];
• [A; A; A]
• [A, A, A]
• >> B = [A, zeros(3,2); zeros(2,3), eye( 2 ) ] ?
Built in Matrix Functions
Function Description
diag return diagonal M.E as a vector
eye identity matrix
magic magic squares
ones matrix of ones
rand randomly generated matrix
zeros matrix of zeros
Built in Matrix Functions
== equal
~= not equal
< less than
<= less than or equal
> greater than
>= greater than or equal
& AND
| OR
~ NOT
Branching Constructs
end
if < condition 1 >,
< program 1>
else
< program2 >
end
Looping Constructs
for i = 1 : n , for i = 1 : n ,
< program>, for j = 1 : n ,
end A(i,j) = i/j ;
end
end
• While Loops:
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot of the
Sine Function')
Multiple Graphs
t = 0:pi/100:2*pi;
y1=sin(t);
y2=sin(t+pi/2);
plot(t,y1,t,y2)
grid on
Multiple Graphs
x = 0 : .01 : 2 * pi;
y1= sin (x);
y2 =sin (2*x);
y3 = sin (4*x);
plot(x,y1,‘--',x,y2,‘-‘,x,y3,‘+')
grid
title ('Dashed line and dotted
line graph')
Multiple Plots
t = 0:pi/100:2*pi;
y1=sin(t);
y2=sin(t+pi/2);
subplot(2,2,1)
plot(t,y1)
subplot(2,2,2)
plot(t,y2)
Three Dimensional Graphics
x = -1:.1:1 ;
y = -1:.1:1;
for i=1:1:length(x)
for j=1:1:length(y)
z(i,j)=x(i)^2+y(j)^2;
end
end
mesh(z);
Graph Functions (summary)
• plot (x,y) linear plot
• plot (x,y1,x,y2) multiple plots on the same graph
• mesh(z) 3-D graph
• stem (x) discrete plot
• xlabel (‘X-axis label ’) add X-axis label
• ylabel (‘Y-axis label ’) add Y-axis label
• title (‘title of plot’) add graph title
• subplot (m,n,p) divide figure window
• grid add grid lines
• hold hold current graph in the figure
• zoom allow zoom in/out using mouse
• figure create new figure window
• pause wait for user response