MATLAB handout no2

advertisement
MATLAB
Handout No. 2
Source: (Mastering Matlab 6: A Comprehensive Tutorial and Reference – Prentice Hall, 2001)
This is a supplement to handout No. 1







Array and Array Mathematics
conditional and logical operators
for, while, and case loops
input command
Saving and loading .mat data
1-D plots
Simple Exercises
A- Array and Array mathematics
o To create a matrix: (look how the rows are separated)
>> g=[1 2 3;0 -1 -2;1 4 -8]
g=
1 2 3
0 -1 -2
1 4 -8
>>h=[3 4 5;-1 4 9;-4 -6 1]
h=
3 4 5
-1 4 9
-4 -6 1
You can perform the matrix operations (rules of linear algebra must hold):
g+h
h-g
2*g
g*h
element by element division: g. /h
inv(g) (matrix inversion)
rank(g) Matrix rank – among others, it gives an idea of number of
linearly independent equations in a liear system
eig(g)
eigenvalues of matrix g [think of it as roots of the
characteristic polynomial)
size(g)

Explore the following:
o ones(3)
o rand(4)
o eye(3) Important identity matrix
o check this out:

*
 a=[1 4 5];
 k=diag(a)
From our matrix g above (explore the following)
o g(2:3)
o g(2:3,:)
o g(:,3)
o g(2,1)+g(3,2)
k=[ ] (this is a way of initializing an array as empty vector)
B- Relational and Logical Operations
a. The typical < , > , < = , > = , = = , ~= (not equal)
b. & , |, ~ (AND, OR, NOT)
c. look at the simple code:
x=2;
if x>=3
y=6;
else
y=7
end
An example with logical operators:
if(a==2 & b==5)
r=20
else
r=30
end
C- Control Flow
a. for loops
example:
for t=1:2:20 % the default step is 1- the step here is 2
y(t)=sin(20*t);
end
b. While Loop
example:
x=10;
while x >1
x=x-2
end
x
c. Another form of the if-else-end
if expression1
commands evaluated if expression1 is true
elseif expression2
commands evaluated if expression2 is true
elseif expression3
commands evaluated if expression1 is true
else
command evaluated if no other expression is true
end
d. Switch – Case construction
example:
x=3;
units ='m';
switch units
case {'inch','in'}
y=x*2.54;
case {'meter','m'}
y=x/100;
case{'centimeter','cm'}
y=x;
otherwise
disp('unknown units'),units
y=nan;
end
y
Extra: Try-Catch-Block
e. This is to have user control for error trapping. With this command, errors
that are found by Matlab are captured and thus the user has the ability to
control how Matlab responds to errors.
Example:
x =ones(2,3)
disp('hit any key to continue')
pause % Hit any key to continue
y=eye(2)
disp('hit any key to continue')
pause %
try
z=x*y % of course this will not work – mismatch of dimensions.
catch
z=nan;
disp('x and y are not of appropriate diemnsions')
end
z
Note: type help catch and explore it.
Now, modify the line:
x=x*y to read x’*y … (transpose of X times y)
When using the try-catch .. we did not get the error .. the flow continued.
Useful information .. Please try each of the instructions and explore ..
D- Input command
This is a user input instruction
type help input
Here is an example:
age=input('what is your age ')
name=input('what is your name
','s')
disp(' here is the data you entered')
disp(' ')
disp(' your age is ')
age
disp(' ')
disp('your name is')
name
E-Saving and loading data files.
Let us now save a .mat file to the working directory and load it from the working
directory
.mat file is typically the data file
Note: of course you can do DLL with Excel.
please do the following:
in the Matlab Command window, type dir. This will list the files available in the
working directory.
type dir *.mat
there will probably be no .mat files yet.
note: you can also change directories and do many of the dos commands from the
matlab window.
It will be essential in some cases to run some programs and save only certain
variables. Following that, we probably want to clear the workspace before
loading the desired variables. This is similar to local variables in function calls.
please read through the steps of the following program and run it. make sure you
understand it.
clear
t= 0:0.01:10;
y=sin(t)
x=4*y;
% the variables in the workspace are now t,x,and y
who % this will list the workspace variables
% suppose we want to save in the file mydata only the variables t,x
save mydata t x
% now, let us explore the data we have created
t
disp('press any key to continue')
pause %
x
disp('press any key to continue')
y
disp('press any key to continue')
% now let us clear the workspace variables
clear
% now let us confirm we did that
who
% chek the directory -- please remember this
dir *.mat
%now let us load the file from the directory
load mydata
who
t
disp('press any key to continue')
x
disp('press any key to continue')
E- 1-D plots
type the following sample program and explore the plots features.
Make sure you bring the figure plot to the front of the active windows to see the
changes.
clear
t=0:0.1:2*pi;
y1=sin(t);
y2=cos(t);
plot(t,y1)
pause(5)
plot(t,y2)
Now, let us do some formatting of the plots
on the active figure (plot of y2)
go to the insert tools and add x-label, y-label, title, and legend
-
go to the edit tools and and select “axis properties” change the scales.
At this point, we are ready to do a little more control with plots:
active labeling and legends
plot formats
subplots
type the following example and make sure you understand the different steps.
note: The command clf clears the contents of a figure
clear
t=0:0.1:2*pi;
y1=sin(t);
y2=cos(t);
plot(t,y1)
grid % this places a grid on the figure
pause(5)
plot(t,y2)
grid
clf % to clear figure contents
plot(t,y1,t,y2) % to plot both, of vourse, we could have done plot(t,[y1' y2'])
% the reason for the transpose is that y1, and y2 are originally column
% vectors ... of course there are lots of more tricks .. thinks of
% matrices!!!
grid
xlabel('time - seconds')
ylabel('voltage - volts')
title('1-D plot demos')
legend('the sine function','the cosine function')
%note: the legend is declared for the first, then second, third, .. and so
%on plots.
pause(5)
% let us clear the current figure and do the following:
plot(t,y1,'*',t,y2,'-.',t,y1-2,'.')
grid
legend('sine plot','cosine plot','sine plot with offset')
The next topics will cover the following:
integration and differentiation (numerically and symbolically)
2-D and 3-D plots
function calls and local/global declaration of variables.
GUI functions and User Interface Utilities
LaPlace transformation and inverse LaPlace transformation
Step(unit and non unit) and Impulse response of a dynamical systems
Transfer function and State Space forms
Many control systems related commands (lots of them)
Simulink and its great features.
Before we go on to a more advanced phase, let us have a few exercises.
Solve each of the following and turn in your results to the instructor. Recall, use the
Matlab help as a guide. This will help build your knowledge and experience with
Matlab.
create a Malab file for each of the following exercises. example: ex1.m
Ex: -1
enter the following vectors/matrices:
A= [2 4 7
-1 3 5
1 0 4]
B = [4
3
2]
C=[1 4 -2]
-
Determine the eigenvalues of matrix A
Determine the product of A *B
print the transpose of A
Ex-2
write a program that uses if else statements to do the following:
define x =2, y=3, z=4;
based on the user input (numbers 1, 2, 3, or 20}
if the input is equal to 1 then print the result of r = x+y+z
if the input is equal to 2, then print the result of r = 2x+3y-z
if the input is >=3 and <20, print the result of r = x
if the input is >=20, print the result of r = z
Ex -3
write a for loop that will do the following:
the loop goes from i=0 up to I = 20
x = i^2
inside the loop, build a vector of I = [I i];
inside the loop, build a vector of X=[X x]
outside the loop, plot X versus I with x-label being the “count”, y-label
being “square function”, title being “Ex-4”
repeat the above plot, however, the plot now is yellow colored dots!!
Download