See the Course Notes page for a collection of online Matlab Resources.
See the following for extended versions of the notes below on basic Matlab calculations and operations with arrays (vectors and matrices)
Calculations from Gilat (optional text for course)
Matlab is primarily for numerical calculations not symbolic calculations.
We will view it as being strictly for numerical (i.e. floating point) calculations.
No required statement terminator
Optional statement terminator ;
(semi-colon) suppresses output (will
use when programming)
:
(colon) reserved for other purposes---plays central in
the language, providing key features of Matlab's powerful
array manipulation capabilities
Equals sign =
used for assignment
Regular parentheses ( )
used for array indexing
Square brackets [ ]
used for in-place array construction
(analogous to usage for lists in Maple)
Percent sign %
is the comment character
Single quotes ('this is a string') used for strings not double quotes ("this is not a string")
Comma ,
can be used to separate multiple expressions on one line
Although Matlab is proprietary software, there is another system, octave, which is a no-cost open source clone of Matlab. The version of octave that currently ships is strictly command-line based, and its plotting facilities---which use gnuplot---are rudimentary in comparison to Matlab's. However, in my Matlab coverage, I try to stick to features that are available in octave and, in fact, almost all of the code that I have written for the class is tested to ensure that it runs on both systems.
Those of you running Linux or Mac OSX can install octave on your own machines and can use it to work on at least some of the Matlab homework, as well as your projects. If you do so, you will need to be careful to:
Not use any features of octave unavailable in Matlab (for example, octave has an optional extended syntax for most control structures designed to increase readability of code).
Ensure that anything you write in octave does run as you intend on the version of Matlab installed on the course machines.
Installation in this case is straightforward: octave is a standard packages available in any of the standard distributions including Ubuntu and Mageia.
In the case of OSX, however, you will first need to set up one of the available software management systems that facilitate installation of many of the command-line and X-base applications used in the Linux world. See the course Software page for more details.
In principle octave can be installed on Windows, but I have never tried to do so and, from what I can tell, it is likely to be more hassle than it is worth.
/phys210/$LOGNAME/matlab
directoryFollowing our usual practice, first create a directory which will contain Matlab code that you will copy and write during the labs.
IMPORTANT
In contrast to other directories of this sort that we have created,
this one will not be located in your home directory, but rather
in /phys210/$LOGNAME
, which is the same place that your homework
directories are located.
Execute the following
% cd /phys210/$LOGNAME
% pwd
/phys210/phys210f
% mkdir matlab
% cd matlab
% pwd
/phys210/phys210f/matlab
% date > date
% ls
We will not proceed until everyone has successfully done this.
As we shall see, in contrast to Maple, there is no particular benefit in starting Matlab from the command line, so our normal practice will be to launch it from the panel; do so now if you haven't already.
Let's try typing a few Matlab commands. Again, note that the syntax is sometimes different than it is for Maple.
I realize that there will be confusion, not least since you're still working on your Maple homework: on the other hand, by the end-of the course you'll be multilingual!
Note that the Matlab prompt is >>
and that the output below looks a bit
different from what you'll see in the Matlab window since my output
was generated using octave, which we will discuss briefly next
lab, and which is an open-source Matlab clone. As noted above,
%
is the comment character and you don't need to type any
of the comment lines.
% SCALARS ...
210
ans = 210
% Any value not explicitly assigned to a variable is assigned
% to the special variable 'ans' by default
>> 410
ans = 410
% Assign a value to a variable --- use =
>> a = 210
a = 210
>> a
a = 210
% pi is predefined but NOT protected ...
pi
ans = 3.1416
% Change output format to show full precision (about 16 digits)
>> format long
>> pi
ans = 3.14159265358979
>> b = pi / 3
b = 1.04719755119660
>> sin_b = sin(b)
sin_b = 0.866025403784439
>> cos_b = cos(b)
cos_b = 0.500000000000000
>> sum_b = sin_b^2 + cos_b^2
sum_b = 1
>> sum_b - 1
ans = 0
>> Sum_b = 1 + 2
Sum_b = 3
>> sum_b , Sum_b
sum_b = 1
Sum_b = 3
>> sqrt(2)
ans = 1.41421356237310
>> exp(1)
ans = 2.71828182845905
>> log(exp(1))
ans = 1
>> log10(10^2)
ans = 2
% ROW VECTORS ...
% Use [ ] to create vectors in-line, separating elements with white space or commas
vec1 = [2, 3, 5, 7]
vec1 =
2 3 5 7
>> vec2 = [11 13 17 19]
vec2 =
11 13 17 19
% Index using regular parenthesis
>> vec1(3)
ans = 5
>> vec1 = 1 : 10
vec1 =
1 2 3 4 5 6 7 8 9 10
>> vec1(8)
ans = 8
>> vec1a = 1 : 1 : 10
vec1a =
1 2 3 4 5 6 7 8 9 10
>> vec1 - vec1a
ans =
0 0 0 0 0 0 0 0 0 0
>> vec2 = 10 : -1 : 1
vec2 =
10 9 8 7 6 5 4 3 2 1
>> vec1 + vec2
ans =
11 11 11 11 11 11 11 11 11 11
% Colon operates with floats as well
>> format short
>> vec3 = 0.0:0.25:1.5
vec3 =
0.00000 0.25000 0.50000 0.75000 1.00000 1.25000 1.50000
% MATRICES ...
% Define row by row, separating rows with semi-colons
mat1 = [ [1, 0, 0]; [0, 1, 0]; [0, 0, 1] ]
mat1 =
1 0 0
0 1 0
0 0 1
% Index with ( ), supplying 2 indices
>> mat1(1,1)
ans = 1
>> mat1(2,1) = -1
mat1 =
1 0 0
-1 1 0
0 0 1
% Rows defined using colon operator
>> mat2 = [ [1:4]; [5:8]; [9:12]; [13:16] ]
mat2 =
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
% Transpose operator
>> mat2'
ans =
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
% 4 x 4 matrix of random numbers between 0 and 1
>> mat3 = rand(4)
mat3 =
0.800587 0.739155 0.707768 0.129989
0.980077 0.594170 0.925259 0.365658
0.895373 0.525012 0.079183 0.997303
0.244606 0.644317 0.318224 0.066753
% Matrix inverse computed in two ways
>> inv(mat3)
ans =
4.77502 -2.44260 0.51729 -3.64688
0.43686 -0.96806 0.17759 1.79887
-3.66848 3.32607 -0.86490 1.84601
-4.22570 2.43849 0.51347 2.18060
>> mat3^(-1)
ans =
4.77502 -2.44260 0.51729 -3.64688
0.43686 -0.96806 0.17759 1.79887
-3.66848 3.32607 -0.86490 1.84601
-4.22570 2.43849 0.51347 2.18060
% When operating on matrices, * is matrix multiplication
>> mat3 * mat3
ans =
2.03088 1.48628 1.34795 1.08888
2.28486 1.79884 1.43305 1.29183
1.54622 1.65792 1.44312 0.45391
1.12857 0.77372 0.81572 0.58922
>> mat3 * inv(mat3)
ans =
1.0000e+00 3.3307e-16 2.6368e-16 -1.6653e-16
-1.5543e-15 1.0000e+00 1.1102e-16 7.7716e-16
-1.7764e-15 8.8818e-16 1.0000e+00 8.8818e-16
-2.2204e-16 1.6653e-16 6.2450e-17 1.0000e+00
% eye: built in command for generating the identity matrix
>> eye(4)
ans =
Diagonal Matrix
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
>> mat3 * inv(mat3) - eye(4)
ans =
-8.8818e-16 3.3307e-16 2.6368e-16 -1.6653e-16
-1.5543e-15 8.8818e-16 1.1102e-16 7.7716e-16
-1.7764e-15 8.8818e-16 0.0000e+00 8.8818e-16
-2.2204e-16 1.6653e-16 6.2450e-17 0.0000e+00
%-----------------------------------------------------------
% MATRIX: m rows by n columns (m x n)
% ROW VECTOR: 1 row by n columns (1 x n)
% COLUMN VECTOR: m rows by 1 column (m x 1)
%-----------------------------------------------------------
% COLUMN VECTORS ...
% Define like a Matrix, each row is one value so don't need
% inner [ ] .
vc1 = [2; 3; 5; 7]
vc1 =
2
3
5
7
% Can also transpose a row vector (that's a ' to transpose)
>> vc2 = [2, 3, 5, 7]'
vc2 =
2
3
5
7
% linspace command: another way to generate a row vector with uniformly spaced
% elements
%
% Syntax: linspace( <first element>, <last element>, <# of elements> )
>> vec4 = linspace(0.0, 1.0, 21)
vec4 =
Columns 1 through 8:
0.00000 0.05000 0.10000 0.15000 0.20000 0.25000 0.30000 0.35000
Columns 9 through 16:
0.40000 0.45000 0.50000 0.55000 0.60000 0.65000 0.70000 0.75000
Columns 17 through 21:
0.80000 0.85000 0.90000 0.95000 1.00000
% PLOTTING ...
% Plot a vector of sin(x)'s vs x with 1001 uniformly spaced values
% of x from -2*Pi to 2*Pi
% ; suppresses output
vx = linspace(-2*pi, 2*pi, 1001);
vsinx = sin(vx);
plot(vx, vsinx)
Carefully enter the following in a terminal window (copy and paste recommended):
% matlab -nosplash -nodesktop
You should see something like this appear on your terminal
< M A T L A B (R) >
Copyright 1984-2014 The MathWorks, Inc.
R2014a (8.3.0.532) 64-bit (glnxa64)
February 11, 2014
To get started, type one of these: helpwin, helpdesk, or demo.
For product information, visit www.mathworks.com.
>>
This is a trig function: \( cos(x) \)
Try entering Matlab commands to perform this calculation:
\[ a = -73.4 \] \[ b = 6.0 \] \[ c = 13.1 \] \[ x = \frac{-b + \sqrt{b^2 - 4ac}}{2a} \]
Then check that
\[ a x^2 + b x + c\]
is (approximately) 0.
Now, compute the determinant of a 3 x 3 matrix:
\[ A = \left[ \begin{matrix} 2.1 & 0.2 & 2.3 \\ 2.4 & 2.5 & 3.6 \\ 3.7 & 3.8 & 4.9 \end{matrix} \right ] \]
\[ \det A = ? \]
HINT
You can probably guess what Matlab command you should use to compute the \( \det() \)
Exit a command-line Matlab session using
>> exit
or
>> quit
Add definitions to your ~/.aliases
file to do the following:
/phys210/$LOGNAME/matlab
Change to your home directory and make a backup of your .aliases file
% cd
% cp .aliases .aliases.O
Now use your editor to add the following lines to your ~/.aliases
.
I am using the alias names mat
and cdm
. You can use others
if you prefer.
alias cdm='cd /phys210/$LOGNAME/matlab'
alias mat='matlab -nosplash -nodesktop'
As always, be sure to save the file after making changes, but don't exit the editor until you're sure that you've added the alias correctly by opening a new terminal session, typing ...
% cdm
% pwd
/phys210/phys210f/matlab
... and verifying that the working directory is /phys210/$LOGNAME/matlab
and
% mat
.
.
.
>> exit
to ensure that command-line Matlab starts.
IMPORTANT
Once you have done this, execute the following
% cd
% cp .aliases /phys210/$LOGNAME/matlab
Either in the lab, or using a ssh client on one of your personal machines and running command-line Matlab, work through the calculations
which reproduces some of those done in the first chapter of an older edition of Gilat MATLAB An Introduction with Applications (the optional text for the course).
We will start next day with
a little in-lab "quiz" on the material that will involve translating
expressions of the sort we did in command-line Matlab, but only
using scalar values, and various of the common mathematical functions
such as sin
, cos
, cosd
, sind
, exp
, ln
, sqrt
, ...
Now that we have had a chance to work with Matlab interactively a bit, you may suspect that I'm going to ask you to start entering Matlab commands in text files, and then have them input into Matlab in some fashion.
And if you do suspect this, you're correct!
We'll get on to this shortly, but first we need to make a little digression and talk about the notion of a script, which in other programming languages might simply be called a program, or a main program.
In the Maple notes and homework I've actually used the term script a lot, first defining it loosely as a sequence of Maple commands that would typically be prepared in a text file. Now, our programming in Maple was largely restricted to writing procedures, that is, pieces of code that took one or more specific pieces of input---the arguments---and which returned a specific value.
Apart from interactive use (i.e. at the Maple command-line), procedures in and of themselves aren't particularly useful since if there isn't a human around to invoke them---i.e. to type in their names with suitable arguments---they can't be used.
This is where the notion of a program comes in. If we want a process that truly runs autonomously on a computer, i.e. without human intervention, then there has to be a "top-level" set of commands that we give to the machine and which the machine then executes start to finish. This is precisely what we mean by a program (or main program), and the basic Maple scripts that we coded to test the procedures that we wrote constitute simple programs.
In out Matlab programming, we will also focus on writing procedures---except now they will be called functions, but we will also spend more time writing "main programs" or, as they are conventionally called in the Matlab world, scripts. Scripts (main programs) will also play a central role in all of your term projects, since they are what you will use at the "top level" to generate and analyze your results.
So from now on, when you hear me say script, think ...
set of commands that I will give Matlab to execute, and which will do something, but for which the "functional" picture of returning some specific value isn't really useful
If you want a simple concrete example, think of writing a program (script) to make a plot of \(sin(x)\) vs \(x\). The function \(sin(x)\) gets called time and time again in whatever process it is we use to generate the plot, and the fact that it returns the correct thing every time it gets handed some value of \(x\) is crucial. However we need that top level program that actually does the calling and plot-making so that we can see what the plot looks like, and, although we can perhaps think abstractly of the image of the graph on the screen as the "return value" of the main program, it isn't a very useful viewpoint for us.
You should also be aware that the distinction between main programs (scripts) and subprograms (procedures, functions, subroutines, ...) can get blurry and that most programs of any length will get broken down into simpler constituents for two key reasons:
Manageability/Intelligibility: Pieces of code longer than about a page tend to become difficult to understand and maintain.
Factorization: Complex code often contains pieces that are
repeated---not always verbatim, but possibly with relatively
small modifications that can be defined algorithmically.
It is then natural to write these pieces as procedures/functions,
which the main program (and other procedures of course) can call
in as many places as necessary.
To sum up, we will be considering two types of code in Matlab:
Scripts or main programs which we will define as some arbitrary set of Matlab commands that we have coded to do something, but which will generally not hand back a "return value" to the environment.
Functions (the analogs of Maple procedures) that will take some number or arguments (perhaps none) and will return one or more specific values to the invoking environment.
help
commandYou can get online help at the command prompt for any Matlab command using
the help
command:
Example
>> help linspace
linspace Linearly spaced vector.
linspace(X1, X2) generates a row vector of 100 linearly
equally spaced points between X1 and X2.
linspace(X1, X2, N) generates N points between X1 and X2.
For N = 1, linspace returns X2.
Class support for inputs X1,X2:
float: double, single
See also logspace, colon.
Overloaded methods:
distributed/linspace
codistributor2dbc/linspace
codistributor1d/linspace
codistributed/linspace
gpuArray/linspace
Reference page in Help browser
doc linspace
This works for both the command-line and desktop versions of Matlab.
The desktop version also supplies an extensive searchable/browseable
help facility that you can start via the help icon on the HOME
toolbar or using the F1
key. In particualr, if you highlight
a word in the command window (such as a command name), and then
depress F1
, help for that topic, should it be available, will
appear.
.m
filesAs with other programming languages Matlab source files that define scripts or functions are typically prepared in text files, and thus typically created with text editors.
By convention, these source files have a
.m
extension and we will consider it a cardinal rule that Matlab source files must have a.m
extension. As usual, the filename "stem" i.e. the part that appears before the extension should be composed of alphanumeric characters and the underscore (and not start with a numeral), but otherwise can be whatever you wish.
Thus, the following are valid names for Matlab source files:
foo.m
bar9.m
mysin.m
MyScript.m
I_like_typing_a_lot.m
while the following are not:
foo
bar9.c
mysin.f
MyScript.py
I_like_typing_a_lot.not
We have now seen three examples of programming environments where input comes from the keyboard (terminal) by default, but can be redirected from another source, typically a file:
In the shell (bash) we use input redirection: <command> < <file>
In gnuplot we use load "<gnuplot-commands>"
In Maple we use read <maple-commands>
In Matlab life is even easier. For concreteness, and in a vivid demonstration of my lack of imagination, let's say we have a script file
foo.m
containing some sequence of commands that we want Matlab to execute. Then provided that one or both of the following is true ...
foo.m
lives in the directory in which Matlab is executing (as
with all Unix programs, Matlab does have a working directory
at any given time)
foo.m
lives in one of the directories in the Matlab user's
Matlab path
then the script can be executed (i.e. input can be redirected to the script file) simply by typing the filename stem
>> foo
I.e. we don't have to use a special command to do the redirection,
we simply need to type the name of the file, being sure---and this
is very important---not to include the .m.
extension.
Let's quickly see how this works.
In a terminal window, change to your personal Matlab directory
/phys210/$LOGNAME/matlab
that you made in the last lab. Since I had you create an alias to
do the appropriate cd
-ing, you should be able to type
% cdm
to do this, otherwise type
% cd /phys210/$LOGNAME/matlab
Now start your text editor from the shell prompt to create the
.m
file hello.m
, being sure to run the editing session in the
background so that you can continue to run commands.
% kate hello.m &
or
% gedit hello.m &
Enter the following command in the file and save it:
'Hello world'
Be sure to enclose the string in single quotes. Note that this
is a valid Matlab command since it is a valid string and thus
has a valid value. Like Maple, Matlab
will evaluate the expression and simply regurgitate the
value--i.e. the string--assigning it to ans
since we aren't'
t explicitly assigning it to another variable name.
Now, and again this is important, from the same command line start up command-line Matlab. Once more, we defined an alias to do this, so you should be able to simply type
% mat
If that doesn't work then just type
% matlab
and wait for the GUI to appear,
Just don't start Matlab by clicking on its icon on the desktop panel. This example will not work if you do that.
BEGIN ASIDE
From time to time (more often than I would like), I find that command-line Matlab takes an inordinate amount of type to start up and present the prompt. In my impatience I have found that if this happens, typing Ctrl-C one or more times can hasten Matlab along.
END ASIDE
Now type
>> hello
at the command line, and be awestruck by the result.
ans =
Hello world!
And there, you've just executed your first Matlab script (program)!
The rest of this course is mere details.
Notice what happens if we type the full filename
>> hello.m
Undefined variable "hello" or function "hello.m".
so again, remember that you only have to (and must) type what is before the
.m
extension to execute the commands in the source file. Similarly,
if the source file does not have a .m
extension then it can't be
executed in this simple fashion.
startup.m
)As I alluded to above, in addition to the working directory, Matlab
will look for .m
files to execute in the list of directories
maintained in its path (distinct from the bash path for bash commands,
but clearly identical in concept). We can see the list of
those directories (which can and will vary from user to user) using
the path
command
>> path
and you'll see that there's a whole boatload of directories in the path.
Scroll back to the top and look at the first entry or two. You should see
MATLABPATH
/home2/phys210f/Documents/MATLAB
but with phys210f
replaced with your account name.
The first time Matlab starts up on any user account, it creates a Matlab startup folder (directory) which on Unix systems:
Is called Matlab (i.e. the name of the folder/directory is Matlab)
Is located in ~/Documents (i.e. in the subdirectory Documents of the user's home directory)
The designers of Matlab might suggest that the proper place to put your Matlab code would be within this folder, but we're anarchists and I need to be able to snoop on what you're doing, so we're going to deposit our code in
/phys210/$LOGNAME/matlab
i.e. where we just created hello.m
.
Naturally then, we had better add that directory to our Matlab path so that we can start Matlab any way we like---including by clicking on the panel icon---and our source files will still be found when we type their de-extensioned names.
There's an easy way to do this since Matlab, like any self-respecting programming environment, has a special startup file which
Can contain an arbitrary sequence of Matlab commands
Will be executed every time Matlab starts
On Unix systems, this file is called
startup.m
and is located in the startup directory, i.e. its full pathname is
~/Documents/MATLAB/startup.m
You're now going to copy a basic "course default" startup.m
and then modify it so that your own personal Matlab code directory
will be in your own personal Matlab path.
Follow these instructions carefully.
Working in the terminal window, exit the command-line Matlab session:
>> exit
Change to your Matlab start up directory
% cd
% cd Documents/MATLAB
% pwd
/home2/phys210f/Documents/MATLAB
% ls -a
Unless you've been mucking around with Matlab on your own, the
ls -a
command should display nothing (the -a
option means "all", i.e.
show hidden files as well).
Copy the course default startup.m
file
% cp ~phys210/Documents/MATLAB/startup.m .
Make a backup copy of the file
% cp startup.m startup.m.O
Edit the file
% kate startup.m &
or
% gedit startup.m &
You should see 6 lines in the file, four of which are comments, since
their first non-whitespace character is a %
. (if you don't have line numbering
enabled in your editor you should, so ask for help as necessary)
Leave the first actual command line
addpath('/home/phys210/matlab');
alone. If you mangle it or delete it, you will experience difficulties in the labs to follow, as well as with the Matlab homework and your term projects.
Change the last line
addpath('/phys210/phys210/matlab');
so that the second occurrence of phys210
is your login name.
So, for example, my demo account's version becomes
addpath('/phys210/phys210f/matlab');
Save the file, but don't exit the editor yet.
Test what you have done: Start desktop Matlab by clicking on the panel icon.
Type
>> hello
at the prompt, and verify that Matlab cheerfully replies
ans =
'Hello world!'
If it does, exit the editing session, go back to the terminal command line (you don't have to exit your Matlab session) and type exactly the following---best to cut and paste the command:
% date > /phys210/$LOGNAME/matlab/done
Wait for the rest of the class to complete this setup.
If things aren't working as advertised, ask for help immediately since we won't proceed to the quiz itself until everyone in the lab completes the setup procedure.
From time to time Matlab may terminate abnormally. In such instances, the applications may generate a "crash" file, which can be useful for the developers/maintainers of the software to examine in case the "crash" is due to a bug.
These files will usually be deposited in your home directory, and will have names of the form:
matlab_crash_dump.<something>
You can safely remove these if and when they appear.
To complete this quiz, your answers, which will
be various Matlab statements and
commands, must be entered in the .m
script file
/phys210/$LOGNAME/matlab/q1.m
(i.e. lower-case-Q-one).
IMPORTANT
Note that this file, like hello.m
, must live in the
directory
/phys210/$LOGNAME/matlab
not your home directory or somewhere else. Again, provided that you have set things up properly, you can create this file by returning to the command line, or opening a new terminal session if necessary and executing
% cdm
% gedit q1.m &
or
% cdm
% kate q1.m &
You can proceed in one of two ways: but in both cases you
will need to edit (create/modify) q1.m
.
Using your text editor, enter all of the needed Matlab expression
(commands) into q1.m
, continually saving the file and reexecuting
the commands by typing
>> q1
at the Matlab command line.
IMPORTANT: if your commands are not executed
when you type q1
, ask for help!
Type the commands interactively and once you've computed each calculation to your satisfaction, transfer the commands to your editing session, using copy and paste for efficiency and to reduce the probability of introducing errors. Again, be sure that you save the file frequently as go along and you should still execute
>> q1
from time to time (probably after every time you record a
calculation in the file) to ensure that all of your computations have been correctly transferred to q1.m
.
IMPORTANT: if your commands are not executed
when you type q1
, ask for help!
If you adopt approach 1 (which you can bet is the way that I would do it), you may still find it helpful to experiment at the command line.
Indeed, always experiment when you are learning a new programming environment. If you're wondering whether such and such will work, go ahead and try it. At worst you'll be generating a little excess heat by getting the CPU/core working a little more than when you're staring at the screen.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% PHYS 210 Intro Computational Physics
%
% q1.m: Instructor's solution
%
% Note: I have appended _k to all names to facilitate grading of
% student work with a script.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Q1.1
>> q11_k = 23 * (-8 + sqrt(607)/3) + (40/8 + 4.7^2)^2
q11_k = 738.75
% Q1.2
>> q12_k = cos(5*pi/6) * sin(7*pi/8)^2 + tan(pi/6*log(8)) / (sqrt(7) + 2)
q12_k = 0.28462
% Q1.3
>> x_k = 5.3
x_k = 5.3000
>> z_k = 7.8
z_k = 7.8000
>> q13_k = (x_k*z_k) / (x_k/z_k)^2 + 14*x_k^2 - 0.8*z_k^2
q13_k = 434.13
% Q1.4
>> A_k = 2
A_k = 2
>> B_k = -7
B_k = -7
>> C_k = -10
C_k = -10
>> x0_k = -3
x0_k = -3
>> y0_k = 4
y0_k = 4
>> d_k = abs(A_k*x0_k + B_k*y0_k + C_k) / sqrt(A_k^2 + B_k^2)
d_k = 6.0439
% Q1.5
>> vr_q15_k = [6, 8*3, 81, exp(2.5), sqrt(65), sin(pi/3), 23.05]
vr_q15_k =
6.00000 24.00000 81.00000 12.18249 8.06226 0.86603 23.05000
% Q1.6
>> vc_q16_k = [44; 9; log(51); 2^3; 0.1; 5*tand(25)]
vc_q16_k =
44.00000
9.00000
3.93183
8.00000
0.10000
2.33154
% Q1.7
>> W_k = 3.1 : 1.0 : 10.1
W_k =
Columns 1 through 7:
3.1000 4.1000 5.1000 6.1000 7.1000 8.1000 9.1000
Column 8:
10.1000
% Q1.8
>> Z_k = linspace(-1.0, 2.5, 8)'
Z_k =
-1.00000
-0.50000
0.00000
0.50000
1.00000
1.50000
2.00000
2.50000
% Q1.9
>> R_k = [0:4:28; 69:-1:62; linspace(1.4,-0.7,8)]
R_k =
Columns 1 through 7:
0.00000 4.00000 8.00000 12.00000 16.00000 20.00000 24.00000
69.00000 68.00000 67.00000 66.00000 65.00000 64.00000 63.00000
1.40000 1.10000 0.80000 0.50000 0.20000 -0.10000 -0.40000
Column 8:
28.00000
62.00000
-0.70000
% Q1.10
>> V_k = [3.1 4.1 5.9 2.6 5.3 5.8 9.7 9.3]
V_k =
3.1000 4.1000 5.9000 2.6000 5.3000 5.8000 9.7000 9.3000
% Q1.11
>> V_round_k = round(V_k)
V_round_k =
3 4 6 3 5 6 10 9
% Q1.12
>> V_int_k = fix(V_k)
V_int_k =
3 4 5 2 5 5 9 9
Here are some special variables whose values are predefined in Matlab.
Note that, in contrast to Maple for example, none of the variable names are protected, so we must be careful.
In particular, if you are using Matlab to do calculations with complex
numbers, then you need to be very careful with your usage of the
names i
and j
which, as we have seen in Maple, are often natural
names to choose for loop variables.
>> format long
%-----------------------------------------------------------------------
% pi: our dear old transcendental friend.
%-----------------------------------------------------------------------
>> pi
ans = 3.14159265358979
%-----------------------------------------------------------------------
% eps: the value of "machine epsilon": the SMALLEST number in the
% floating point doman such that
%
% 1 + eps = 1
%
% Can be intepreted as the relative accuracy of basic floating point
% calculations such as the multiplication of two values.
%-----------------------------------------------------------------------
>> eps
ans = 2.22044604925031e-16
>> 1
ans = 1
>> 1 + eps
ans = 1.00000000000000
>> (1 + eps) - 1
ans = 2.22044604925031e-16
>> (1 + eps / 2) - 1
ans = 0
>> (1 + eps / 1.5 ) - 1
ans = 2.22044604925031e-16
% I'll leave the explanation of the behaviour of the last expression
% as an exercise for the curious
%-----------------------------------------------------------------------
% Inf: Infinity
% NaN: Not a number
%
% Two values defined by the IEEE-754 standard for floating point
% arithmetic to formally represent:
%
% Inf -> "Overflow": A number too large in magnitude to be
% represented in the floating point model, division
% by 0 e.g.
% NaN -> The result of an undefined floating point calculation,
% such as the square root of a negative value, with
% a restriction to real values (note MATLAB will happily
% return a COMPLEX value for sqrt(-2) etc.)
%
% Producing Inf's and/or NaN's in your code is to be viewed as a
% "bad thing", i.e. an indication that your algorithm is doing
% something it shouldn't.
%-----------------------------------------------------------------------
>> Inf
ans = Inf
>> 1/0
ans = Inf
>> -1/0
ans = -Inf
>> NaN
ans = NaN
% Here's one way to generate a "not-a-number":
>> 0/0
ans = NaN
% Inf and NaN are both "contagious". If they appear in an algebraic
% expression, then you can be sure that the expression will evaluate
% to one of them!
>> Inf + 10
ans = Inf
>> NaN^2
ans = NaN
>> Inf * NaN
ans = NaN
% This will not and should not evaluate to 0!
>> Inf - Inf
ans = NaN
%-----------------------------------------------------------------------
% Two distinct names for the unit imaginary complex value.
%
% i -> sqrt(-1)
% j -> sqrt(-1)
%
% Note: j is frequently used in engineering.
%-----------------------------------------------------------------------
>> i
ans = 0 + 1i
>> j
ans = 0 + 1i
>> sqrt(-1)
ans = 0 + 1i
>> sqrt(-pi)
ans = 0.000000000000000 + 1.772453850905516i
>> i * i
ans = -1
>> i * j
ans = -1
>> j * j
ans = -1
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% COMMANDS THAT GENERATE ARRAYS WITH SPECIAL ELEMENTS: zeros, ones, eye
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%=======================================================================
% Convention for MATLAB array "constructors"
%
% Two arguments supplied
%
% <command>(m, n)
%
% First argument, m -> number of rows
% Second argument, n -> number of columns
%
% Array returned is m x n
%
% One arguments supplied
%
% <command>(n)
%
% Array returned is n x n (square)
%=======================================================================
%-----------------------------------------------------------------------
% zeros
%-----------------------------------------------------------------------
% 3 x 4 matrix
>> zm = zeros(3, 4)
zm =
0 0 0 0
0 0 0 0
0 0 0 0
% length 5 row vector (1 x 5 matrix)
>> zr = zeros(1, 5)
zr =
0 0 0 0 0
% length 6 column vector (6 x 1 matrix)
>> zc = zeros(6,1)
zc =
0
0
0
0
0
0
% Equivalently, using transpose operator '
>> zc1 = zeros(1,6)'
zc1 =
0
0
0
0
0
0
% Invocation with single argument returns square matrix of values
>> zsq = zeros(4)
zsq =
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
%-----------------------------------------------------------------------
% ones
%-----------------------------------------------------------------------
>> om = ones(2, 5)
om =
1 1 1 1 1
1 1 1 1 1
>> omsq = ones(3)
omsq =
1 1 1
1 1 1
1 1 1
>> or = ones(1, 10)
or =
1 1 1 1 1 1 1 1 1 1
>> oc = ones(11, 1)
oc =
1
1
1
1
1
1
1
1
1
1
1
%-----------------------------------------------------------------------
% Use ones and scalar multiplication to generate other arrays
% with identical values.
%-----------------------------------------------------------------------
>> twos = 2 * ones(5)
twos =
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
>> pis = pi * ones(1,5)
pis =
3.1416 3.1416 3.1416 3.1416 3.1416
%-----------------------------------------------------------------------
% eye
%-----------------------------------------------------------------------
>> eye(5)
ans =
Diagonal Matrix
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
>> eye(1)
ans = 1
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ARRAY ADRESSING
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%-----------------------------------------------------------------------
% NOTE: When indexing ANY array, we need to be careful not to use
% index values that are out of range (in MATLAB parlance, which
% "exceed the matrix dimensions")
%
% Because what you are looking at is "auto-generated" by a script,
% I cannot include any MATLAB statements here that produce errors as
% examples.
%-----------------------------------------------------------------------
>> vr = linspace(0.0, 1.0, 6)
vr =
0.00000 0.20000 0.40000 0.60000 0.80000 1.00000
>> vc = [-1.0 : 0.25 : 1.0]'
vc =
-1.00000
-0.75000
-0.50000
-0.25000
0.00000
0.25000
0.50000
0.75000
1.00000
>> m = [vr; 2 * vr; 3 * vr; 4 * vr]
m =
0.00000 0.20000 0.40000 0.60000 0.80000 1.00000
0.00000 0.40000 0.80000 1.20000 1.60000 2.00000
0.00000 0.60000 1.20000 1.80000 2.40000 3.00000
0.00000 0.80000 1.60000 2.40000 3.20000 4.00000
%=======================================================================
% Extraction of single element -- remember, use (), NOT []
%=======================================================================
>> vr(1)
ans = 0
>> vr(3)
ans = 0.40000
>> vc(2)
ans = -0.75000
>> vc(4)
ans = -0.25000
>> m(1,3)
ans = 0.40000
>> m(4,6)
ans = 4
%-----------------------------------------------------------------------
% end: special index for final element along any dimension
%
% For a(m, n):
%
% a(i, end) -> last element of i-th row
% a(end, j) -> last element of j-th column
%
% For vectors of either type (row / column)
%
% v(end) -> last element
%-----------------------------------------------------------------------
>> vr
vr =
0.00000 0.20000 0.40000 0.60000 0.80000 1.00000
>> vr(end)
ans = 1
>> vc
vc =
-1.00000
-0.75000
-0.50000
-0.25000
0.00000
0.25000
0.50000
0.75000
1.00000
>> vc(end)
ans = 1
>> m
m =
0.00000 0.20000 0.40000 0.60000 0.80000 1.00000
0.00000 0.40000 0.80000 1.20000 1.60000 2.00000
0.00000 0.60000 1.20000 1.80000 2.40000 3.00000
0.00000 0.80000 1.60000 2.40000 3.20000 4.00000
>> m(1, end)
ans = 1
>> m(4, end)
ans = 4
>> m(end, 5)
ans = 3.2000
>> m(end,end)
ans = 4
%=======================================================================
% Simultaneous extraction of multiple elements:
%
% Another extremely powerful feature of MATLAB: array's can
% indexed with row VECTORS of indices.
%
% Will start with simple examples here and then continue with the
% topic next day ...
%=======================================================================
v = 2 * (1:10)
v =
2 4 6 8 10 12 14 16 18 20
% Select 2nd, 5th and 7th elements:
>> v( [2, 5, 7] )
ans =
4 10 14
% Equivalently:
>> v( [2 5 7] )
ans =
4 10 14
% Select first and last:
>> v( [1 end] )
ans =
2 20
% Select second and second-to-last:
>> v( [2 end-1] )
ans =
4 18
%-----------------------------------------------------------------------
% Any command / expression that evaluates to a row vector can be
% used to index.
%-----------------------------------------------------------------------
% Most notable in this respect are vectors generated using the
% colon notation
% First 3:
>> v( 1:3 )
ans =
2 4 6
% Last 5:
>> v( end-4:end )
ans =
12 14 16 18 20
% Last 5 in reverse order:
>> v( end:-1:end-4 )
ans =
20 18 16 14 12
%-----------------------------------------------------------------------
% Special case: single colon selects ALL elements
%-----------------------------------------------------------------------
% Of no use for vectors since we can simply use name --- but of great use
% for matrices and higher dimensional arrays.
>> v
v =
2 4 6 8 10 12 14 16 18 20
>> v(:)
ans =
2
4
6
8
10
12
14
16
18
20
% Why does v(:) return a column vector? Technical: related to the
% way that storage is laid out in memory.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Using a Colon : In Array Addressing
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Vectors (review)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> v = [4 15 8 12 34 2 50 23 11]
v =
4 15 8 12 34 2 50 23 11
>> u = v(3:7)
u =
8 12 34 2 50
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Matrices
%
% General syntax:
%
% <matrix>(:, :) = all elements of matrix
% <matrix>(:, n) = all elements of columnn
% <matrix>(m, :) = all elements of row m
% <matrix>(:, m:n) = all elements between columns m
% and n inclusive
% <matrix>(m:n, :) = all elements between rows m
% and n inclusive
% <matrix>(m:n, p:q) = all elements between rows m
% and n, and columns p and q
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> A = [1:2:11; 2:2:12; 3:3:18; 4:4:24; 5:5:30]
A =
1 3 5 7 9 11
2 4 6 8 10 12
3 6 9 12 15 18
4 8 12 16 20 24
5 10 15 20 25 30
>> b = A(:, 3)
b =
5
6
9
12
15
>> c = A(2, :)
c =
2 4 6 8 10 12
>> E = A(2:4, :)
E =
2 4 6 8 10 12
3 6 9 12 15 18
4 8 12 16 20 24
>> F = A(1:3, 2:4)
F =
3 5 7
4 6 8
6 9 12
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Selecting multiple elements of arrays by indexing
% with vectors.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> vv = 10:20
vv =
10 11 12 13 14 15 16 17 18 19 20
>> vv([2 3 5 9])
ans =
11 12 14 18
>> v = 4:3:34
v =
4 7 10 13 16 19 22 25 28 31 34
>> [3, 5, 7:10]
ans =
3 5 7 8 9 10
>> u = v( [3, 5, 7:10] )
u =
10 16 22 25 28 31
>> A = [10:-1:4; ones(1,7); 2:2:14; zeros(1,7)]
A =
10 9 8 7 6 5 4
1 1 1 1 1 1 1
2 4 6 8 10 12 14
0 0 0 0 0 0 0
% Select rows 1, 3 and 4
>> A([1, 3, 4], :)
ans =
10 9 8 7 6 5 4
2 4 6 8 10 12 14
0 0 0 0 0 0 0
% Select colums 2, 3 and 6
>> A(:, [2, 3, 6])
ans =
9 8 5
1 1 1
4 6 12
0 0 0
% Select columns 1, 3, 5, 6 and 7 from rows 1 and 3
>> B = A([1, 3], [1, 3, 5:7])
B =
10 8 6 5 4
2 6 10 12 14
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Adding elements to existing variables.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Adding elements to a vector.
%
% Elements can be added to an existing vector by
% assigning values to the new elements.
%
% If the vector is of length n, and the value assigned
% is for an element with address p which is >= n + 2,
% then elements n + 1, ... p - 1 are implicitly assigned
% the value 0 (default value).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> df = 1:4
df =
1 2 3 4
>> df(5:10) = 10:5:35
df =
1 2 3 4 10 15 20 25 30 35
>> ad = [5 7 2]
ad =
5 7 2
% Increase length of ad to 8 elements ... element 8
% is set to 4, elements 4, 5, 6 and 7 set to 0 (implicitly)
>> ad(8) = 4
ad =
5 7 2 0 0 0 0 4
% This assigns a length 5 row vector to ar, the last
% element is set to 5, elements 1, 2, 3 and 4 to 0
% (implicitly).
>> ar(5) = 24
ar =
0 0 0 0 24
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Elements can also be added to a vector by appending
% (concatenating) existing vectors
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> re = [3 8 1 24]
re =
3 8 1 24
>> gt = 4:3:16
gt =
4 7 10 13 16
>> knh = [re gt]
knh =
3 8 1 24 4 7 10 13 16
% Recall that ' is the transpose operator:
% row' -> column
% column' -> row
>> re'
ans =
3
8
1
24
>> gt'
ans =
4
7
10
13
16
% To concatentate column vectors use ';' between vectors
>> knv = [re'; gt']
knv =
3
8
1
24
4
7
10
13
16
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Adding elements to a matrix.
%
% Rows and/or columns can be added to an existing
% matrix by assigning values to the new rows or columns.
%
% One must be careful in this case since the size of
% the added rows/columns must be compatible with the
% existing matrix.
%
% As was the case for vectors, any matrix elements
% that are implicitly created by an operation that
% changes the size of the matrix, and which are not
% assigned explicit values, are set to 0.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> E = [1 2 3 4; 5 6 7 8]
E =
1 2 3 4
5 6 7 8
% Add a third row.
>> E(3,:) = [10:4:22]
E =
1 2 3 4
5 6 7 8
10 14 18 22
>> K = eye(3)
K =
Diagonal Matrix
1 0 0
0 1 0
0 0 1
% Concatenate E and K: possible since each has 3 rows.
% Result has 3 rows and (4 + 3) = 6 columns.
>> G = [E K]
G =
1 2 3 4 1 0 0
5 6 7 8 0 1 0
10 14 18 22 0 0 1
>> H = G'
H =
1 5 10
2 6 14
3 7 18
4 8 22
1 0 0
0 1 0
0 0 1
% Concatenate H and K: possible since each has 3 columns.
% Result has 3 columns and (7 + 3) = 10 rows.
% As with vectors, use ';' to concatenate columns.
>> M = [H; K]
M =
1 5 10
2 6 14
3 7 18
4 8 22
1 0 0
0 1 0
0 0 1
1 0 0
0 1 0
0 0 1
>> AW = [3 6 9; 8 5 11]
AW =
3 6 9
8 5 11
% This adds 2 rows and 3 cols to AW, new elements
% that are not explictly set are assigned 0
>> AW(4,5) = 17
AW =
3 6 9 0 0
8 5 11 0 0
0 0 0 0 0
0 0 0 0 17
% This assigns a 3 x 4 array to BG, sets "corner" element
% to 15, rest to 0
>> BG(3,4) = 15
BG =
0 0 0 0
0 0 0 0
0 0 0 15
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Deleting elements of arrays.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% An element, or range of elements, can be deleted
% by assigning "nothing" to them: the syntax for
% nothing is [] (a set of square brackets with nothing
% inside except 0 or more characters of whitespace.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> kt = [2 8 40 65 3 55 23 15 75 80]
kt =
2 8 40 65 3 55 23 15 75 80
% Delete the 6th element: note that this modifies kt.
>> kt(6) = []
kt =
2 8 40 65 3 23 15 75 80
% Delete elements 3, 4, 5 and 6 of (the modified) kt.
>> kt(3:6) = []
kt =
2 8 15 75 80
>> mtr = [5 78 4 24 9; 4 0 36 30 12; 56 13 5 89 3]
mtr =
5 78 4 24 9
4 0 36 30 12
56 13 5 89 3
% Delete columns 2, 3 and 4.
>> mtr(:,2:4) = []
mtr =
5 9
4 12
56 3
% What happens if we try to delete one element of a
% matrix? Error?
% mtr(1:1) = []
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Built-in functions for handling arrays.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MATLAB has a rich set of functions for creating,
% manipulating and determining properties of arrays.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% length(<vector>)
%
% Returns the number of elements in <vector>.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> a = [5 9 2 4]
a =
5 9 2 4
>> length(a)
ans = 4
>> length(linspace(0, 1, 10001))
ans = 10001
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% size(<matrix>)
%
% If <matrix> is m x n, size returns the row
% vector [m n]
%
% i.e. size returns the "dimensions" of a matrix,
% or of an array in general.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> A = [6 1 4 0 12; 5 19 6 8 2]
A =
6 1 4 0 12
5 19 6 8 2
>> size(A)
ans =
2 5
%-------------------------------------------------------
% IMPORTANT: The following illustrates another powerful
% piece of MATLAB syntax which we will use frequently.
%
% Many MATLAB functions, such as size, return more than
% Sometime, as in the case of size, the values comprise
% a vector, but this is not necessarily the case. For
% example, the first value returned could be a scalar,
% the second a vector, the third a matrix etc.
%
% If we want to "capture" more than one return value
% we need to use an assignment statement in which
% a "vector" of variable names appears on the left hand
% side.
%
% Syntax:
%
% [<name1>, {<name2>, ..., <namen>}] = <function_n>(...)
%
% or
%
% [<name1> {<name2> ... <namen>}] = <function_n>(...)
%
%
% where <function_n> is a function that returns n values.
% and the { } enclose optional quantities---i.e. there
% can be 1, 2, ... n names in the "assignment vector".
%-------------------------------------------------------
>> [mA, nA] = size(A)
mA = 2
nA = 5
%-------------------------------------------------------
% Again, we will be saying assignments of this type
% throughout our usage of MATLAB.
%-------------------------------------------------------
% size applied to vectors.
%
% A row vector of length n is a 1 x n matrix
% A column vector of length m is a m x 1 matrix
>> size([1:100])
ans =
1 100
>> size([1:200]')
ans =
200 1
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% reshape(<matrix>, m, n)
%
% If <matrix> is p x q, then returns a new matrix
% which is m x n and which contains the same elements
% as <matrix>, but in an order which is best
% illustrated by example, as below.
%
% Note: m * n must be equal to p * q
%
% This function is a little hard to master, but is worth
% doing so if you want to become proficient in Matlab!
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Make a 3 x 4 matrix containing the integers 1 through
% 12 with consecutive integers down the successive
% columns.
>> Ar1 = reshape(1:12, 3, 4)
Ar1 =
1 4 7 10
2 5 8 11
3 6 9 12
%------------------------------------------------------
% Again, as I mentioned tangentially when we noted that
% indexing a row vector with : returns a column vector,
% this column-wise behaviour is intimately related to
% the fact that MATLAB array elements are laid out
% in memory in column-major order, so that a(i,j) and
% a(i+1,j) are contiguous in storage, NOT a(i,j) and
% a(i,j+1). This convention goes back to the FORTRAN
% programming language which is even older than your
% instructor.
%------------------------------------------------------
% To get consecutive integers along rows, just use
% transpose.
>> Ar2 = reshape(1:12, 4, 3)'
Ar2 =
1 2 3 4
5 6 7 8
9 10 11 12
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% diag(<vector>)
%
% If <vector> is of length n, returns an n x n
% matrix with the elements of <vector> along the
% diagonal, and zeros elsewhere.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> v = [7 4 2]
v =
7 4 2
>> A = diag(v)
A =
Diagonal Matrix
7 0 0
0 4 0
0 0 2
>> I7 = diag(ones(1,7))
I7 =
Diagonal Matrix
1 0 0 0 0 0 0
0 1 0 0 0 0 0
0 0 1 0 0 0 0
0 0 0 1 0 0 0
0 0 0 0 1 0 0
0 0 0 0 0 1 0
0 0 0 0 0 0 1
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% diag(<matrix>)
%
% If <matrix> is m x n, then returns a COLUMN vector of
% length m whose elements are the main diagonal of
% <matrix>(:, 1:m)
%
% If <matrix> is m x m (i.e. square), this is simply
% the main diagonal of the matrix.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> A = [1 3 4; 4 5 6; 7 8 9]
A =
1 3 4
4 5 6
7 8 9
>> vec = diag(A)
vec =
1
5
9
>> B = [1 3 4; 4 5 6]
B =
1 3 4
4 5 6
>> vecB = diag(B)
vecB =
1
5
% Transpose the next result to minimize wasted vertical space!
>> diag(eye(10))'
ans =
1 1 1 1 1 1 1 1 1 1
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Strings and string manipulation.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 1) In MATLAB, a string is an array (vector) of
% characters.
%
% 2) Strings can be created by enclosing an arbitrary
% sequence of characters (other than a single forward
% quote), including whitespace and special characters,
% within a pair of single (forward) quotes ' '
%
% 3) If you want to include a single quote within a
% string, type two consecutive quotes.
%
% 4) Strings can be assigned to variables using the
% usual syntax for variable assignment.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> s = 'foo'
s = foo
>> a = 'FRty 8'
a = FRty 8
>> B = 'My name is Matt'
B = My name is Matt
>> c = 'That''s ridiculous!!'
c = That's ridiculous!!
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Since a string is a vector of characters, individual
% characters in a string, or consecutive sets of
% characters (substrings), can be extracted and/or
% assigned values using the standard addressing
% operations.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> B(4)
ans = n
>> B(12)
ans = M
>> c(8:17) = 'capricious'
c = That's capricious!!
>> alphabet = 'abcdefghijklmnopqrstuvwxyz'
alphabet = abcdefghijklmnopqrstuvwxyz
>> vowels = alphabet([1 5 9 15 21 25])
vowels = aeiouy
Your answers to Quiz 2 must be entered in the .m
script file
/phys210/$LOGNAME/matlab/q2.m
(i.e. lower-case-Q-two).
Start an editing session with that file now.
% cdm
% kate q2.m &
or
% cdm
% gedit q2.m &
NOTE
If the alias cdm
doesn't work for you, please get help from
one of the TAs or myself.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PREAMBLE / WARNING
%
% As I have already mentioned, one of the principal
% design goals of Matlab was to make calculations in
% linear algebra---which underly much of numerical
% analysis---straightforward.
%
% In particular, Matlab is designed so that operations
% such as matrix-matrix mutiplication are trivial.
%
% Thus, is A and B are compatible matrices (i.e. so that
% the number of columns of A equals the number of rows
% of B, then we can compute the MATRIX PRODUCT of
% A and B by simply typing
%
% >> A * B
%
% Although this is very convenient, and allows us to
% write in a natural way many expressions involving matrices
% and vectors that would be cumbersome to code in
% other languages, the power comes with a "gotcha",
% which is this:
%
% Since * (as well as / and ^) have linear-algebra
% meanings when used with matrices, and, further,
% since column vectors and row vectors are special
% types of matrices, we must use a different syntax
% when we want to perform so-called elementwise
% operations.
%
% For example, if v is the row vector ...
%
% >> v = [1 2 3]
%
% ... then you might expect that
%
% >> v * v
%
% would return ...
%
% v = [1 4 9]
%
% But it will not, as you can readily verify. Instead
% Matlab gives the error mesage ...
%
% Error using *
% Inner matrix dimensions must agree.
%
% ... which may seem cryptic now, but which you should
% understand by the time we work through these notes.
%
% IMPORTANT: Get USED to seeing this error message
% when working with arrays and matrices:
%
% - Know what it (probably) means (i.e. what you did
% wrong
%
% - Know how to fix the (likely) problem by using the
% correct syntax for the operation (typically
% multiplication, division or expnonetiation)
% you wish to perform on the array(s).
%
% To sum up there are two ways that we can use arithmetic
% operations when working with arrays in Matlab.
%
% 1. elementwise, where we need to prepend a .
% (period/dot) to the arithmetic operator:
%
% .*
% ./ left division (usual division)
% .\ right division (a\b -> "b divided by a")
% .^
% .+ (. not required but won't hurt)
% .- (. not required but won't hurt)
%
% Example:
%
% >> a = [1 2 3] .* [4 5 6]
%
% a = 4 10 18
%
% 2. "Array-wise", where we use the usual arithmetic
% operators but where the operators are interpreted as
% matrix-matrix operations
%
% + (identical to .+
% -
% *
% / Left division
% \ Right division
%
% Example:
%
% m1 = [[1 2]; [3 4]]
%
% m1 =
%
% 1 2
% 3 4
%
%
% m2 = [[4 3]; [2 1]]
%
% m2 =
%
% 4 3
% 2 1
%
% m1 * m2
%
% ans =
%
% 8 5
% 20 13
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Arithmetic operations between a scalar and an array
%
% If one of the operands of an elementary operation
% involving +, -, *, or / is a scalar and the other
% is an array, A, then the operation is applied
% (distributed) to each element of A, yielding a result
% that is also an array with the same dimensions as
% A.
%
% In short, "what you get is what you expect"!
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
v = 1:5
v =
1 2 3 4 5
>> v1 = v + pi
v1 =
4.1416 5.1416 6.1416 7.1416 8.1416
>> v2 = 3.1 * v
v2 =
3.1000 6.2000 9.3000 12.4000 15.5000
>> v3 = v / 5
v3 =
0.20000 0.40000 0.60000 0.80000 1.00000
>> v4 = 2 * v + 6
v4 =
8 10 12 14 16
>> m = [1 2 3; 4 5 6]
m =
1 2 3
4 5 6
>> m1 = 3 * m
m1 =
3 6 9
12 15 18
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NOTE: The exponentiation (power) operator ^ can
% NOT be used % in this way, e.g. v^2 will NOT return
% the vector [1 4 9 15 25]. Rather, Matlab returns an
% error message:
%
% >> [1:5]^2
%
% Error using ^
% Inputs must be a scalar and a square matrix.
% To compute elementwise POWER, use POWER (.^) instead.
%
% As the message suggests, the elementwise syntax discussed
% below must be used instead.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Addition and Subtraction
%
% For addition and subtraction, matrix/array operation
% is always an element-by-element operation.
%
% If arrays are added or subtracted then:
%
% 1) They must have identical sizes.
%
% 2) The arrays are added or subtracted elementwise
% to produce the result.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> VectA = [8 5 4]
VectA =
8 5 4
>> VectB = [10 2 7]
VectB =
10 2 7
>> VectC = VectA + VectB
VectC =
18 7 11
>> A = [5 -3 8; 9 2 10]
A =
5 -3 8
9 2 10
>> B = [10 7 4; -11 15 1]
B =
10 7 4
-11 15 1
>> C = A + B
C =
15 4 12
-2 17 11
>> D = 3 * A - B + 6
D =
11 -10 26
44 -3 35
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Array (Matrix) Multiplication>
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Matrix multiplication in MATLAB is denoted by *
% and is defined according to the standard rule of
% linear algebra: namely
%
% If
% A is an m x n matrix with elements a(i,j)
%
% and
% B is an n x p matrix with elements b(j,k)
%
% then
% C = A * B is an m x p matrix with elements c(i,k)
%
% defined by
% n
% c(i,k) = Sum [ a(i,j) x b(j,k) ]
% j=1
%
% NOTE: For this operation to be well defined,
% the number of columns of A must equal the number of
% rows of B.
%
% MNEMONIC: Arrange all of the dimensions in a single
% row:
%
% --A-- --B--
% m x n n x p
% m x p
% ------C------
%
% ^ ^
% | |
% ------------- "Inner dimensions" must match.
%
% ... which explains the error message one sees when
% executing something like:
%
% >> [1 2 3] * [1 2 3]
%
% Error using *
% Inner matrix dimensions must agree.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> A = [1 4 2; 5 7 3; 9 1 6; 4 2 8]
A =
1 4 2
5 7 3
9 1 6
4 2 8
>> B = [6 1; 2 5; 7 3]
B =
6 1
2 5
7 3
>> C = A * B
C =
28 27
65 49
98 32
84 38
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% D = B * A
%
% would generate an error message since the number of
% columns of B is not equal to the number of rows of A
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> F = [1 3; 5 7]
F =
1 3
5 7
>> G = [4 2; 1 6]
G =
4 2
1 6
>> F * G
ans =
7 20
27 52
% Matrix multiplication isn't commutative in general.
>> G * F
ans =
14 26
31 45
% The commutator of F and G (fundamental in quantum
% mechanics).
>> F * G - G * F
ans =
-7 -6
-4 7
% A row vector ...
AV = [2 5 1]
AV =
2 5 1
% ... and a column vector of the same length ...
BV = [3; 1; 4]
BV =
3
1
4
% ... define two distinct types of products:
%------------------------------------------------------
% (1) The inner product, or dot product.
%
% m x n n x p -> 1 x n n x 1 -> 1
%
% Vectors must be of the same length n and
% the result is a single number (scalar).
%------------------------------------------------------
>> AV
AV =
2 5 1
>> BV
BV =
3
1
4
>> AV * BV
ans = 15
%------------------------------------------------------
% (2) The outer product (may be less familiar to
% you, but can also be useful in many circumstances).
%
% m x n n x p -> n x 1 1 x p -> n x p
%
% Vectors do not have to be the same length and
% the result is a matrix.
%------------------------------------------------------
>> BV
BV =
3
1
4
>> AV
AV =
2 5 1
>> BV * AV
ans =
6 15 3
2 5 1
8 20 4
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Element-By-Element Operations
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% As already noted above, the following binary operators
%
% * multiplication
% \ right division
% / left division (will define/use later)
% ^ exponentiation
%
% can be applied to arrays in an element-by-element
% fashion by prefixing the operator with a '.'
%
% .* element-by-element multiplication
% .\ element-by-element right division
% ./ element-by-element left division
% .^ element-by-element exponentiation
%
% NOTE: When using element-by-element operations
% between arrays, the arrays MUST be the same size.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> A = [2 6 3; 5 8 4]
A =
2 6 3
5 8 4
>> B = [1 4 10; 3 2 7]
B =
1 4 10
3 2 7
>> A .* B
ans =
2 24 30
15 16 28
>> C = A ./ B
C =
2.00000 1.50000 0.30000
1.66667 4.00000 0.57143
>> B .^ 3
ans =
1 64 1000
27 8 343
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Using element-by-element operations to compute a
% function at many values of its argument.
%
% Handy for making plots of functions, for example.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> x = [1:8]
x =
1 2 3 4 5 6 7 8
>> y = x.^2 - 4*x
y =
-3 -4 -3 0 5 12 21 32
>> z = linspace(0, 1, 11)
z =
Columns 1 through 8:
0.00000 0.10000 0.20000 0.30000 0.40000 0.50000 0.60000 0.70000
Columns 9 through 11:
0.80000 0.90000 1.00000
>> y = (z.^3 + 5*z) ./ (4*z.^2 - 10)
y =
Columns 1 through 8:
-0.00000 -0.05030 -0.10244 -0.15840 -0.22051 -0.29167 -0.37570 -0.47799
Columns 9 through 11:
-0.60645 -0.77352 -1.00000
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% We can also use the elementwise notation with the
% addition and subtraction operators, but it is
% unnecessary.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> [ 1 2 3 4] .+ [5 6 7 8]
ans =
6 8 10 12
>> [ 1 2 3 4] + [5 6 7 8]
ans =
6 8 10 12
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Using Arrays In MATLAB Built-in Math Functions.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% When any of MATLAB's built in math functions is
% invoked with an array argument, the output is an
% array with identical size of the input, and with
% elements whose values are the results of applying
% the function to the corresponding elements of
% the input array.
%
% Again this is a case where "what you get is what you
% expect"!
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> x = [0:pi/6:pi]
x =
0.00000 0.52360 1.04720 1.57080 2.09440 2.61799 3.14159
>> y = cos(x)
y =
Columns 1 through 6:
1.0000e+00 8.6603e-01 5.0000e-01 6.1232e-17 -5.0000e-01 -8.6603e-01
Column 7:
-1.0000e+00
>> d = [1 4 9; 16 25 36; 49 64 81]
d =
1 4 9
16 25 36
49 64 81
>> h = sqrt(d)
h =
1 2 3
4 5 6
7 8 9
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Built In Functions for Analyzing Arrays
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Reduction Functions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Many of the functions described below (those marked
% with an (*)) operate on arrays of general dimensions,
% as well as on vectors. Furthermore, when operating
% on a vector, those functions return a single value.
%
% For higher dimensional arrays, and for matrices in
% particular, such functions generally operate along
% columns (i.e. along the first dimension of the
% array), returning a row vector of values: each value
% in the row vector is the result of applying the
% function to the elements of the corresponding
% column of the original matrix.
%
% As discussed before, the column-wise behaviour
% reflects the fact that arrays are laid out in memory
% in column-wise order (FORTRAN heritage).
%
% One net effect of these functions is thus to reduce
% the dimensionality of the array by one (or, more
% properly, to collapse the length of the first
% dimension to 1). Such functions are therefore often
% termed reductions.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% max(A) (*)
%
% If A is a vector, returns the largest element in
% A
%
% If A is a matrix, returns a row vector containing
% the largest element of each column of A
%
% [d, n] = max(A) (*)
%
% If A is a vector, d is the largest element
% in A and n is the (first) index where the largest
% value occurs.
%
% If A is a vector, the values are computed using
% column-wise operations.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> A = [5 9 2 4 11 6 11 1]
A =
5 9 2 4 11 6 11 1
>> C = max(A)
C = 11
>> [d, n] = max(A)
d = 11
n = 5
>> AA = [1 3 2; 4 1 3; 8 11 12; -2, 6, 100]
AA =
1 3 2
4 1 3
8 11 12
-2 6 100
>> CC = max(AA)
CC =
8 11 100
>> [dd, nn] = max(AA)
dd =
8 11 100
nn =
3 3 4
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% min(A) (*)
%
% Operates precisely as max(A), but returns minimum
% values.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> A = [5 9 2 4 11 6 11 1]
A =
5 9 2 4 11 6 11 1
>> C = min(A)
C = 1
>> [d, n] = min(A)
d = 1
n = 8
>> AA = [1 3 2; 4 1 3; 8 11 12; -2, 6, 100]
AA =
1 3 2
4 1 3
8 11 12
-2 6 100
>> CC = min(AA)
CC =
-2 1 2
>> [dd, nn] = min(AA)
dd =
-2 1 2
nn =
4 2 1
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% sum(A) (*)
%
% If A is a vector: Returns the sum of V's elements.
%
% If A is a matrix: Returns a row vector of the
% column-wise sums
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> A = [5 9 2 4]
A =
5 9 2 4
>> sum(A)
ans = 20
>> AA = [1 3 2; 4 1 3; 8 11 12; -2, 6, 100]
AA =
1 3 2
4 1 3
8 11 12
-2 6 100
>> sum(AA)
ans =
11 21 117
% Compute the sum of all elements.
>> sum(sum(AA))
ans = 149
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% prod(A) (*)
%
% If A is a vector: Returns the product of V's elements.
%
% If A is a matrix: Returns a row vector of the
% column-wise products.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> A = [5 9 2 4]
A =
5 9 2 4
>> prod(A)
ans = 360
>> AA = [1 3 2; 4 1 3; 8 11 12; -2, 6, 100]
AA =
1 3 2
4 1 3
8 11 12
-2 6 100
>> prod(AA)
ans =
-64 198 7200
% Compute the product of all elements.
>> prod(prod(AA))
ans = -91238400
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Statistical Functions (assuming A is a vector)
%
% (These are all reductions.)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% mean(A) (*)
%
% Returns the mean value of elements of A (i.e.
% computes the arithmetic average)
%
% median(A) (*)
%
% Returns the median value of elements of A
%
% std(A) (*)
%
% Returns the standard deviation of elements of A
%
% Once more, if A is a matrix, the operations are applied
% column-wise, and a row vector of results are returned.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> vals = [1 2 3 3 4 4 4 5 6 6 7 7 7 7 7 8 9]
vals =
1 2 3 3 4 4 4 5 6 6 7 7 7 7 7 8 9
>> mean(vals)
ans = 5.2941
>> median(vals)
ans = 6
>> std(vals)
ans = 2.2573
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Miscellaneous Functions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% sort(A) (*)
%
% sort(A, 'descend') (*)
%
% Returns the elements of A sorted in ascending
% order.
%
% NOTE: sort is not a reduction. It
% returns an array of the same size as its input.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> V = [5 9 2 4]
V =
5 9 2 4
>> VA = sort(V)
VA =
2 4 5 9
>> VD = sort(V, 'descend')
VD =
9 5 4 2
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% For a matrix, columns are sorted.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> AA = [1 3 2; 4 1 3; 8 11 12; -2, 6, 100]
AA =
1 3 2
4 1 3
8 11 12
-2 6 100
>> sort(AA)
ans =
-2 1 2
1 3 3
4 6 12
8 11 100
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Sort rows using transpose operator (twice):
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> sort(AA')'
ans =
1 2 3
1 3 4
8 11 12
-2 6 100
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Generation of (Pseudo)-Random Numbers</b>
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% NOTE: As with many languages and software
% systems, the "random" numbers generated by MATLAB
% are actually computed using specific, deterministic
% algorithms, and are thus not truly random: hence
% the nomenclature "pseudo-random".
% However, "good" random number generators, such as
% those used by MATLAB / octave are designed so that
% the sequences of numbers produced share many
% statistical properties with true random values.
%
% Those of you doing term projects with a stochastic
% elements, including (but not necessarily limited
% to)
%
% - Diffusion limited aggregation
% - Ising model
% - Cellular automata traffic simulations
% - Cellular automata forest file modeling
% - Neural network modeling
%
% will need to use rand()
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% rand
%
% Generates a single pseudo-random number, drawn from
% a uniform distribution between 0 and 1 (i.e. the
% probability of getting any number in the range is
% the same). Also note that the generator will never
% produce exactly 0 or exactly 1. We will refer to
% such a value as a "standard random number"
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> rand
ans = 0.61135
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Note the use of commas to separate multiple stmnts
% on a single line in the following.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> for ir = 1:10, rand, end
ans = 0.41255
ans = 0.72202
ans = 0.058483
ans = 0.35825
ans = 0.45345
ans = 0.84823
ans = 0.89264
ans = 0.63722
ans = 0.76469
ans = 0.32526
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% rand(1,n)
%
% Generates an n element row vector of standard
% random numbers.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> a = rand(1,4)
a =
0.099631 0.348564 0.866361 0.318296
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% rand(n)
%
% Generates an n x n matrix of standard random
% numbers.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> b = rand(3)
b =
0.52706 0.39375 0.63753
0.41148 0.19197 0.81872
0.11094 0.76882 0.73267
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% rand(m, n)
%
% Generates an m x n matrix of standard random
% numbers.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> c = rand(2, 4)
c =
0.71206 0.81732 0.56310 0.82445
0.23538 0.91763 0.26436 0.76795
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Array (Matrix) Division
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Matrix division in MATLAB is also associated with
% the rules of linear algebra; and specifically with
% the solution of matrix equations.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Identity Matrix.
%
% As we have seen, this can be generated using the
% eye command.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> I = eye(3)
I =
Diagonal Matrix
1 0 0
0 1 0
0 0 1
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% In linear algebra, the identity matrix is to general
% matrices and vectors as the constant 1 is to real
% numbers, i.e. for any n x m array, A, multiplication
% on the left by the n x n identity matrix I yields
% the original array, A, that is
%
% I A = A
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> A = [1 2; 3 4; 5 6]
A =
1 2
3 4
5 6
>> I * A
ans =
1 2
3 4
5 6
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% In the special case that A is n x n (i.e. square),
% we have
%
% I A = A I = A
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> A = [1 2 3; 4 5 6; 7 8 9]
A =
1 2 3
4 5 6
7 8 9
>> I * A
ans =
1 2 3
4 5 6
7 8 9
>> A * I
ans =
1 2 3
4 5 6
7 8 9
% So I commutes with any square matrix ...
I * A - A * I
ans =
0 0 0
0 0 0
0 0 0
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Inverse of a Matrix
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% If A is a n x n (square) matrix, then the n x n (square)
% matrix B is the inverse of A if and only if
%
% A * B = B * A = I
%
% where I is the n x n identity matrix.
%
% -1
% The inverse of A is often denoted A and can be
% computed in MATLAB either by raising A to the -1
% power, or by using the inv function.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> A = [2 1 4; 4 1 8; 2 -1 3]
A =
2 1 4
4 1 8
2 -1 3
>> B = inv(A)
B =
5.50000 -3.50000 2.00000
2.00000 -1.00000 0.00000
-3.00000 2.00000 -1.00000
>> A * B
ans =
1 0 0
0 1 0
0 0 1
>> B * A
ans =
1 0 0
0 1 0
0 0 1
>> A^-1
ans =
5.50000 -3.50000 2.00000
2.00000 -1.00000 0.00000
-3.00000 2.00000 -1.00000
>> A * A^-1
ans =
1 0 0
0 1 0
0 0 1
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Not all square matrices have inverses. Indeed,
% the necessary and sufficient condition for the n x n
% matrix A to have an inverse is that its determinant
% be non-vanishing.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Determinants
%
% I assume that you have seen the definition of the
% determinant of a matrix, if not, refer to any text
% on linear algebra (or wikipedia)
%
% In MATLAB, the determinant of a (square) matrix can
% be computed using the det function.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> A = [1 2; 3 4]
A =
1 2
3 4
>> det(A)
ans = -2
% The determinant changes sign if two rows are exchanged ...
A = [3 4; 1 2]
A =
3 4
1 2
>> det(A)
ans = 2
% ... or if two columns are exchanged.
>> A = [2 1; 4 3]
A =
2 1
4 3
>> det(A)
ans = 2
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Array (Matrix) Division
%
% MATLAB has 2 types of matrix division, namely
% right and left division. Both are best defined
% in the context of solving matrix equations, but
% first let's look at their operation with scalars:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> 1 / 2
ans = 0.50000
%------------------------------------------------------
% ... which is the usual thing---right division, i.e.
% 2 on the right divides 1 on the left.
%------------------------------------------------------
>> 2 \ 1
ans = 0.50000
%------------------------------------------------------
% ... which is LEFT division, i.e. 2 on the left divides
% 1 on the right (or think of it as the mirror reflection
% of right division)
%------------------------------------------------------
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Left Division \
%
% Left division is used to solve the matrix equation
% (linear system of equations)
%
% A X = B
%
% where A is an n x n matrix, while X and B are column
% vectors of length n.
%
% This equation can be solved by left-multiplying both
% sides with the inverse of A:
%
% -1 -1
% A A X = A B
%
% -1
% I X = A B
%
% -1
% X = A B
%
% This last expression can be defined in terms of the
% left division operator \
%
%
% X = A \ B
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Example: Solving three linear equations
%
% Use matrix operations to solve the following system
% of linear equations
%
% 4x - 2y + 6z = 8
% 2x + 8y + 2z = 4
% 6x + 10y + 3z = 0
%
% Written in matrix-vector form the system is:
%
% - - - - - -
% | 4 -2 6 | | x | | 8 |
% | 2 8 2 | | y | = | 4 |
% | 6 10 3 | | z | | 0 |
% - - - - - -
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> A = [4 -2 6; 2 8 2; 6 10 3]
A =
4 -2 6
2 8 2
6 10 3
>> B = [8; 4; 0]
B =
8
4
0
>> X = A \ B
X =
-1.80488
0.29268
2.63415
% Check the solution
>> A * X
ans =
8.0000e+00
4.0000e+00
2.6645e-15
>> A * X - B
ans =
0.0000e+00
-4.4409e-16
2.6645e-15
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% IMPORTANT note for those solving the time dependent
% Schrodinger equations.
%
% Matlab has special facilities for dealing efficiently
% with matrices whose elements are mostly 0's---so
% called SPARSE MATRICES. In many applications,
% including yours, the non-zeros in the matrix A
% that defines a linear system to be solved are isolated
% to a relatively few DIAGONALS (in your case, 3, so
% the system is tridiagonal).
%
% To make use of the special handling of sparse
% matrices which you should do for reasons of efficiency
% (i.e. your program will run MUCH faster if you use
% them) you need to set up the matrix using the
%
% spdiags
%
% command.
%
% Type
%
% help spdiags
%
% for more information and ask me for assistance should
% you not be able to quickly figure out how to use
% the command to define your system.
%
% Once the correct sparse matrix has been constructed
% using spdiags, you can use the left division operator
% to solve the linear system.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% See the extended version of the notes for a discussion
% of right division (the one we use for scalars) which is
% less commonly used when manipulating matrix-vector
% expressions.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Your answers to Quiz 3 must be entered in the .m
script file
/phys210/$LOGNAME/matlab/q3.m
Start an editing session with that file now.
% cdm
% kate q3.m &
or
% cdm
% gedit q3.m &