===================================================
Math 451
Laboratory 1: Introduction to Linux and Matlab
Date: 2013-01-18
===================================================
Goals for today
----------------------------
- To show you how to use a command-line interpreter interactively
- To show you Matlab
- To show you some basics of the Matlab language
- To show you how to write a Matlab function
- To show you how to write a Matlab script
- To show you how to run a Matlab script
- To show you how to save your work to your PASS account
=================================
Getting Started...
=================================
Check to see if your HP workstation is turned on. If it is not on, please turn
it on.
Push the Linux button in the front of the Belkin box, if it isn't pressed.
Wait for Redhat Linux to give you a login box.
Find the menu at the bottom of the screen labeled "Session".
Open it and select 'GNOME'.
Login with your PSU user name and password.
Welcome to Linux. Your computer will now show you a gui interface with a dock
at the top. The main menu should be in the upper left hand corner, and looks
like a person with a red fedora hat on.
On the desktop is a folder labelled "PASS". This is a link to your university
provided storage space. This is where you want to save your work at the end of
this lab.
The first thing we need to do is get out of this gui to a terminal that shows a
command line.
right-click-on-Desktop -> Open Terminal
This will open up a "terminal window", and the program running inside the window
is called a "shell". "Shell" is the generic term used in the biological sense -
a simple and tough thing surrounding the important stuff. (For example, your
body is a shell for your mind.)
For more information see:
http://en.wikipedia.org/wiki/Shell_%28computing%29
http://en.wikipedia.org/wiki/Unix_shell
Welcome to the command line. In the terminal window, there should be
a line of text something like "[tcr2@lxhammond316-211 ~]$" This is called
a command prompt. It doesn't really matter what it says. The important thing
is that there is a cursor next to it. If you start typing, that's where things
will appear.
The command-line is the oldest computer interface in use, and is incredibly
powerful (before 2001, macs did not have a command-line interface), but also a
little scary because of it's arcane and obscure syntax. Fortunately, only a
few commands are important for us right now.
pwd: Displays the path to the directory you're currently in.
Immediately after login this will be your home directory.
ls: list the contents of the current directory. Use 'ls -l' ('-l' =
'long') to get lots more detail.
cd: Changes the current directory. You can either give it:
- a relative path: 'cd subdirectory'
- an absolute path: 'cd /data/group/subdirectory'
- or use it on it's own to jump straight to your home
man: used to find the manual pages about a command, like 'man ls'
- unfortunately, man(ual) is itself confusing.
- 'man man' will tell you more about man
For more information about common commands, see
http://www.math.psu.edu/treluga/311w/lab2/fwunixref.pdf
http://www.math.psu.edu/treluga/311w/lab2/linuxReferenceCard.pdf
At the shell prompt in the terminal, type
cd Desktop
matlab
This tells the shell to run the Matlab program.
Matlab is a computing language developed by Clive Moler and others in the early
and mid 1980's to make it easier to do calculations involving Matrices
(particularly compared to the core Fortran libraries which were the main tools
of the time). Many aspects of the language have been modernized over the years,
including the introduction of object-oriented data structures, but it remains a
1980's language heavily oriented toward matrix calculations, in large part.
http://www.mathworks.com/index.html
http://en.wikipedia.org/wiki/MATLAB
There are a number of tutorials to help you learn to use Matlab at
http://www.mathworks.com/academia/student_center/tutorials/launchpad.html
===============================================
Matlab
===============================================
% A line beginning with '%' is a comment, and is always ignored
% You do not need to type%in comment lines.
% When you open up matlab, you typically get a gui interface
% with a number of windows. The only important one is the one
% in the center called the "Command Window". Click on it.
% Within this window is a prompt, ">>", followed by a blinking
% cursor. This is where you type in commands.
%%% First, the interpreter works like a common calculator.
2 + 2
4*3
2*3+1
2*(3+1)
2 + 2;
% A command without a semicolon at the end prints out an output.
% A command with a semicolon at the end prints nothing.
x = 2 + 2;
x
disp(3*x);
% Variables are made up of letters and '_', and are used to
% store results as you go. The 'disp' function is a simple way
% to display results, but usually, you can just enter the
% variable name without a semicolon to see its value.
%%%% Using arrows to repeat history commands
%
% You can use the up and down arrows to scroll through your
% history of commands and re-execute things, that you've
% already typed in. Try it.
%%%%%%%% the help command
% The help command is a great way to learn about new and old
% functions in matlab that you might want to try to use. Try
% the following.
help cos
help floor
help elfun
help if
%%%%% Matrices
% matlab is designed to make matrix computations easy. The
% following commands show how you can do some basic operations
% to create and manipulate matrices (also called array's by
% matlab).
% Now, let's create some simple named matrices
v = [ -1,0,1]; % comma's seperate columns
w = [ -1;2;1]; % semicolons seperate rows
A = [ 0,1,2; 3,4,5; 6,7,9]
I = eye(3)
% the 'eye' function is used to create identity matrices
% Elements of matrices are accessed using parenthetical
% index notation. We can extra individual entries as
% follows.
A(1,1)
A(2,1)
A(1,2)
size(A)
% We can perorm simple arithmetic with matrices, of course.
A + 2
-2*A
A + I
A*v
% This command should have FAILED because the vector is a
% row vector and not a column vector
A*w
% the single quote ' is used to perform a transpose
v'
A*v'
% Matlab allows both linear-algebra multiplication of
% matrices and element-by-element multiplication of
% matrices.
A*A
A.*A
% and matrix inverses are possible, though you should avoid
% them -- their error-prone.
inv(A)
A*inv(A)
%%%%%% conditionals and loops
x = rand();
if x > 0.5
disp('x is greater than 0.5 when x = ...');
disp(x);
else
disp('x is less than or equal to 0.5 when x = ...');
disp(x);
end
% if you are in the middle of typing a long command and
% want to cancel it, you can use the CONTROL-C key combination
% You can use range notation to generate sequences.
x = 1:8
y = 0:.5:4
% We us this same notation to construct for-loops in matlab
for x=1:10
disp([ x, x^2 ]);
end
% of course, for-loops can also be nested.
for x=1:4
for y=1:4
disp([x,y,x^2+y^2])
end
end
x = rand(10,1);
for t=1:10
if x(t) > 0.5
disp('x is greater than 0.5 when x = ...');
disp(x(t));
else
disp('x is less than or equal to 0.5 when x = ...');
disp(x(t));
end
end
% But in Matlab, it is almost always faster to operate on
% vectors directly, rather than using for-loops. Another
% way to find the elements of a vector that are greater
% than 0.5 is
x.*(x > 0.5)
% There is much more, but for now, we'll move on to something else.
======================================
Matlab *.m files for custom functions
======================================
% Typing in commands can get tedious, especially when you want to repeat
% something you already typed. The 'up-arrow' will show you old commands, but a
% more useful method is to store you commands in a function file or a script
% file. We'll show you how to create both.
% Often, it is convenient to encapsulate a piece of code inside a function, just
% like in other languages. Follow the procedure above to create a new text file
% called "my_first_function.m".
Right-click-on-Desktop -> Create Document -> Empty File
Enter "my_first_function.m" as the filename.
% Double-click on the file. This will open your file in a
% text-editor. It will be empty at first. Type in the
% following.
function y = my_first_function(x,R)
y = R.*x.*(1-x);
return
% To test your function, return to the Matlab interpretor and
% at the prompt type
>> my_first_function(0.5,3.0)
% If everything works, your answer should be about 0.70711 If you have a bug,
% you can change your function, and then rerun it until you get it right.
======================================
Matlab *.m files for scripts
======================================
% Now, we would like to use "my_first_function.m" to create some plots of the
% solution of the discrete logistic equation. To do this, create a new file on
% the desktop called "my_first_script.m", fill it with the following commands,
% and save it.
%% start of script %%
N = 40;
R = 3.2;
t = 1:N;
x = zeros(1,N);
y = zeros(2,2*N);
x(1) = 1e-5;
y(:,1) = [x(1);0];
for i=1:(N-1)
x(i+1) = my_first_function(x(i),R);
y(:,2*i) = [ x(i); x(i+1) ];
y(:,2*i+1) = [ x(i+1); x(i+1) ];
end
figure(1);
clf;
subplot(2,1,1);
plot(t,x,'bo-');
title('A solution sequence for the discrete logistic');
xlabel('Step');
ylabel('Value');
subplot(2,1,2);
z = linspace(0,1,100);
plot(z,my_first_function(z,R),'r-',[0,1],[0,1],'k-', y(1,:), y(2,:),'bo-');
title('Phasespace cobwebbing of the solution');
xlabel('x_t');
ylabel('x_{t+1}');
xlim([0,1])
ylim([0,1])
%% end of script %%
% what do you thing the output of this script will be?
================================
Running your new Matlab script
================================
Save your file.
Open a new terminal window (right-click on the desktop).
$ cd Desktop
$ ls
% You should see a list of file names including your new text file,
% "my_first_script.m"
$ cat my_first_script.m
% this will list the contents of the file
% Now, return to matlab. At the command prompt, type the
% name of your new script.
>> my_first_script
% This command runs your script. Inspect the output, and see if it does what
% you expected. If you entered part of the script incorrectly, you may see an
% error message. "Debug" your script by trying to find where things are wrong
% and fixing them. The result should be a figure showing part of a solution to
% the discrete logistic difference equation.
That's it. Now you know the basics of matlab. One last thing.
==============================================
Saving your work for another day
==============================================
$ cd ~/Desktop/
$ pwd
% to check that you are in your machine's Desktop directory
$ cp my_first_script.m PASS/
% that's it. Now, your file has been copied to your PASS directory.
% Next time you need it, look there.
% WARNING: IF YOU HAVEN'T COPIED ALL YOUR WORK SOMEPLACE SAFE BEFORE YOU
% LOG OUT, YOU MAY LOSE IT.
Now, close out your session....
System -> Log Out