Académique Documents
Professionnel Documents
Culture Documents
Halmstad University
School of Information Science, Computer and Electrical Engineering
Laboratory 1
Length about 2 hours with supervision.
Even if if you completed the whole Lab-PM during these 2 hours you should try to
find the time to work through this Lab-PM thoroughly afterward.
The last page contains hand-in assignments. You should try to solve them within a
week to be able to follow the pace in the course.
Everything that follows after >> is written in the Matlab Command Window and
indicates what you as a user should write. The % is intended as a comment to that
specific command.
Start Matlab by a double click on the Matlab icon or else by searching for it under
program !
Now, there should be a large window containing several smaller. These could for
instance be: Command Window, Command History and Workspace.
This will of course depend on what version you are currently working in.
This is the desktop of Matlab.
Command Window: Here you can write your own command lines and access your
own files ( m-files), but normally you can also see the output from the calculations in this
window.
Command History: All command lines are saved here and can be seen in the window, but
the same can be achieved by using the arrow button (up). The past command lines can the
be seen in the command window.
Workspace: The variables that have been used or created during the execution will be
shown in this window. Here you can see value, bytes and class.
When you double click on the variables, the elements of the variables become visible.
These three windows should be the default when you start Matlab.
This can of course be altered by Desktop->Desktop Layout or you can construct your
own layout and save it.
Current Directory: The directory where you save your m-files or where you store them.
Matlab prefers that you store your m-files in the directory work, but you can of course
put them anywhere you want.
If you choose to put them in any other directory, you should give the path to the directory
by File-> Set Path or select current directory.
During the course you will need to use the Help Browser in Matlab in order to find out
how a certain command works. In the Help Browser you can also find related command
lines, examples, description, or help with the syntax.
Figure 1
Please note that x has changed its elements and size !
Lets now illustrate how to create an m-file(macro) or if you prefer a small program.
Assume that we have to make a number of command lines before we end up with a plot
in a figure window. If we make an error in the command line then we have to repeat the
command line sequence. A better way, should be to put the command line sequence in an
m-file and just correct the bad command line there. Execute the m-file simply by writing
the name of the m-file in the command window and without the extension .m .
In order to let Matlab find the m-file give the path or make the directory where you have
stored the m-file to your current directory.
Exercise 3: Open an edit window where we can write the command lines. Click on the
white sheet in the menu under File or simply write edit in the command window.
Alternatively
File->New ->M-file. The following is written in the edit window:
------------------------------------------------------------------------------------------------------% M-file created 060118 by Thomas Munther.
t=0:0.01:10; % t goes from 0 to 10 in steps of 0.01.
y1=sin(t);
% everything to the left of the equality sign is an assignment, y1 is
% variable.
plot(t,y1), grid % plots y1 versus t and puts a grid on the plot.
hold
% holds the figure window and allows several plots to be made in the
% same figure.
y2=sin(2*t);
% variable y2 is introduced and calculated.
plot(t,y2)
% plots y2 versus t in the same figure window as above.
title(Exercise 3) % puts a title in our plot.
xlabel(tid)
% gives a label to the x-axis.
ylabel(y)
legend('sin(t)','sin(2*t)')
% puts a box with text for different plots.
----------------------------------------------------------------------------------------------------
Figure 2
Note that title, xlabel, ylabel and legend could have been performed in the figure
window, in the menu under Insert. It looks a bit odd that both curves have the same line
styles. This could well be a problem if we did have a problem with trigonometric
functions. We will try to solve this. Click on the arrow in the menu of the figure window.
Then double click on any of the curves. Enter under Style->LineStyle and change to
dotted line. You can also change the if you want(Line Color) .
There is also a possibility to exclude or exchange values in the plot. Lets illustrate how
this is done.
Double click on any curve and choose Data->YData->y1 and then Edit Data. Now all
plotting values that are used for one of the sine curves are accessible. Change the values
to 2 for all indexes from 10 to 20. Take a new look on the plot !!
This is perhaps not normal procedure in dealing with data, but I am just showing the
possibilities with different tools.
Before we end this take a small look
Enter View->Camera Toolbar and mark it !
Now we get another tools menu in the figure window. By this it is possible with 3D, to
rotate the plot, to make it move over the screen and much much more.
Try it !
By now you have constructed your first m-file. There are two sorts of m-files: command
line and function m-files. Note that an m-file must not begin with a number.
The name must not contain dots or space for nothing else than extension.
>> A=[1 2 3; 4 5 6]
The matrix A has 2 rows and 3 columns.
The first row is: 1 2 3 and the second row is: 4 5 6.
The columns are ordered in a similar manner. Column number one has the element: 1
4
and column number two: 2 and finally column number three: 3
5
6
Each and every element in A is accessible, by using indices:
A(row_index,column_index).
Whats the answer to the following ?
>> A(2,1)+A(1,3)+A(2,3)
Matrices in Matlab does not necessarily only contain real numbers. They can also be
complex. We can even have matrices with text as elements.
If there is only one row in the matrix => we have a row vector.
Only one column in the matrix => a column vector.
And finally the special case: a matrix 1x1 is nothing else than a scalar.
What will happen by doing the following ?
A(1,1)=12
Try to figure out how the commands size and length works!
Exercise 7: Matlab has some own predefined variables aside from the variables that we
make ourselves. You do not need to specify what kind of variables you have introduced.
There is no need for any declaration.
Matlab separates capital and small letters. No variables may begin with a number,
underscore or the swedish letters , and . Variables which are numbers are stored in
matlab like a float with double precision. The class will be double. Since a computer can
not store variables with infinetely high representation we are always limited by the
precision of the storage.
Predefined variables in matlab:
ans
The value of the last calculated expression.
eps
Gives computer precision, distance between 1 and closest float.
pi
3.141592653589793
inf
Defines infinity, defined as 1/0.
i,j
Gives the imaginary unit. Defined as squareroot of -1.
nan
An unidentified number ( Not a Number ).
realmax
Gives the highest float which can be represented by the
computer.
realmin
Gives the smallest float which can be represented by the
computer.
% squareroot of -1
If two operators have the same order of priority. The calculations are carried out from left
to right. Parenthesis can cancel the order of priority.
Evaluate the following:
>> 10/5+2
Matlab gives the answer 4, since the division is carried out before the addition.
>> 10/5+2*3^2
Matlab gives the answer 20, since the evaluation starts with power, then we have:
10/5+2*9, after that division and then multiplication,
2+18, and finally addition
ans=20
Matlab is full of mathematical built-in functions which solves arithmetical expressions.
We will now list some of the functions from the directory elfun.
Write !
>> help elfun
Now we have a long list of mathematical functions, some of them I think you are able to
recognize. Below we have some expressions, try to calculate these by using the help in
Matlab and specifically the directory elfun.
Ie3 + 7M
!!!!
ln I 6 log H5LM
sin H30 L +
4
!!!!!
!
% answer= 0.5599
54
% answer=4.2816
Let us see if we have round off functions in matlab:
Get aquainted with the functions round, fix, floor och ceil !
Exercise 9: Often one wants to save the data or variables to another occasion. Maybe
one wants to save the whole matlab session. This can be done. Commands are put in a
m-file but data or variables are stored in a mat-file ( binary file ) which can be opened
with Workspace Browser.
First have a look in the workspace to find out how your varables look like. Then save
these in a mat-file.
>> save execution1
>> clear
>> load execution1 % collects all the variables stored in the mat-file execution1.mat
Does it work ?
We can also store everything that is displayed in the command window. Like the whole
session both the command lines and the output from Matlab, id est the calculations.
This can be done by:
>> diary exercise9
Everything that follows from now on in the command window will be stored in the asciifile exercise9. Write just anything to get some response from Matlab into the command
window.
diary off
Find the file exercise9 and see if the content in the file is the same that were displayed in
the command window!
--------------------------------------------------------------------------------------------------------Finally a little table of different numeric display formats. Useful for one of the home
assignments and later on as well in the course.
format short
format long
format bank
format rat
format long e
format short e
4 decimal digits
14 decimal digits
2 decimal digits
fractional form
14 decimal digits
4 decimal digits
0.3333
0.33333333333333
0.33
1/3
3.33333333333333e-01
3.3333e-01
eL sin IH 2L2M
bL e2 sin I 5 M
c) ln(6)+log(4)
dL sin2 H 2L
10