Matlab R
Matlab R
David Hiebeler
Dept. of Mathematics and Statistics
University of Maine
Orono, ME 04469-5752
http://www.math.umaine.edu/~hiebeler
I wrote the first version of this reference during the Spring 2007 semester, as I learned R while teaching
my course “MAT400, Modeling & Simulation” at the University of Maine. The course covers population
and epidemiological modeling, including deterministic and stochastic models in discrete and continuous
time, along with spatial models. Half of the class meetings are in a regular classroom, and half are in
a computer lab where students work through modeling & simulation exercises. When I taught earlier
versions of the course, it was based on Matlab only. In Spring 2007, some biology graduate students in
the class who had learned R in statistics courses asked if they could use R in my class as well, and I said
yes. My colleague Bill Halteman was a great help as I frantically learned R to stay ahead of the class.
As I went, every time I learned how to do something in R for the course, I added it to this reference, so
that I wouldn’t forget it later. Some items took a huge amount of time searching for a simple way to do
what I wanted, but at the end of the semester, I was pleasantly surprised that almost everything I do
in Matlab had an equivalent in R. I was also inspired to do this after seeing the “R for Octave Users”
reference written by Robin Hankin. I’ve continued to add to the document, with many additions based
on topics that came up while teaching courses on Advanced Linear Algebra and Numerical Analysis.
This reference is organized into general categories. There is also a Matlab index and an R index at
the end, which should make it easy to look up a command you know in one of the languages and learn
how to do it in the other (or if you’re trying to read code in whichever language is unfamiliar to you,
allow you to translate back to the one you are more familiar with). The index entries refer to the item
numbers in the first column of the reference document, rather than page numbers.
Any corrections, suggested improvements, or even just notification that the reference has been useful
will be appreciated. I hope all the time I spent on this will prove useful for others in addition to myself
and my students. Note that sometimes I don’t necessarily do things in what you may consider the “best”
way in a particular language; I often tried to do things in a similar way in both languages. But if you
believe you have a “better” way (either simpler, or more computationally efficient) to do something, feel
free to let me know.
Acknowledgements: Thanks to Alan Cobo-Lewis and Isaac Michaud for correcting some errors;
and Thomas Clerc, Richard Cotton, Stephen Eglen, Andreas Handel, David Khabie-Zeitoune, Michael
Kiparsky, Andy Moody, Lee Pang, Manas A. Pathak, Rune Schjellerup Philosof, and Corey Yanofsky for
contributions.
Permission is granted to make and distribute verbatim copies of this manual provided this permission
notice is preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the conditions
for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a
permission notice identical to this one.
Permission is granted to copy and distribute translations of this manual into another language, un-
der the above conditions for modified versions, except that this permission notice may be stated in a
translation approved by the Free Software Foundation.
c
Copyright °2007–2009 David Hiebeler
1
D. Hiebeler, Matlab / R Reference 2
Contents
1 Help 3
2 Entering/building/indexing matrices 3
2.1 Cell arrays and lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.2 Structs and data frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3 Computations 6
3.1 Basic computations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.2 Complex numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.3 Matrix/vector computations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.4 Root-finding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.5 Function optimization/minimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.6 Numerical integration / quadrature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.7 Curve fitting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
5 Functions, ODEs 21
7 Graphics 27
7.1 Various types of plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
7.2 Printing/saving graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
7.3 Animating cellular automata / lattice simulations . . . . . . . . . . . . . . . . . . . . . . . 36
9 Miscellaneous 38
9.1 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
9.2 Strings and Misc. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
10 Spatial Modeling 42
1 Help
No. Description Matlab R
1 Show help for a function (e.g. help sqrt, or helpwin sqrt to see help(sqrt) or ?sqrt
sqrt) it in a separate window
2 Show help for a built-in key- help for help(’for’) or ?’for’
word (e.g. for)
3 General list of many help top- help library() to see available libraries,
ics or library(help=’base’) for very
long list of stuff in base package which
you can see help for
4 Explore main documentation doc or helpbrowser (previously it help.start()
in browser was helpdesk, which is now being
phased out)
5 Search documentation for lookfor binomial help.search(’binomial’)
keyword or partial keyword
(e.g. functions which refer to
“binomial”)
2 Entering/building/indexing matrices
No. Description Matlab R
6 Enter
£ a row ¤ vector ~v = v=[1 2 3 4] v=c(1,2,3,4) or alternatively
1 2 3 4 v=scan() then enter “1 2 3 4” and
press Enter twice (the blank line
terminates input)
1
2
7 Enter a column vector
3 [1; 2; 3; 4] c(1,2,3,4)
4
(R does not distinguish between row
· ¸ and column vectors.)
1 2 3
8 Enter a matrix [1 2 3 ; 4 5 6] To enter values by row:
4 5 6
matrix(c(1,2,3,4,5,6), nrow=2,
byrow=TRUE) To enter values by
column: matrix(c(1,4,2,5,3,6),
nrow=2)
9 Access an element of vector v v(3) v[3]
10 Access an element of matrix A(2,3) A[2,3]
A
11 Access an element of matrix A(5) A[5]
A using a single index: in-
dices count down the first col-
umn, then down the second
column, etc.
12 Build the vector [2 3 4 5 6 7] 2:7 2:7
13 Build the vector [7 6 5 4 3 2] 7:-1:2 7:2
14 Build the vector [2 5 8 11 14] 2:3:14 seq(2,14,3)
D. Hiebeler, Matlab / R Reference 4
If you use regular indexing, i.e. w If you use regular indexing, i.e. w =
= v(i), then w will be a 1 × 1 cell v[i], then w will be a list of length 1
matrix containing the contents of the containing the contents of the ith ele-
ith element of v. ment of v.
46 Set the name of the ith ele- (Matlab does not have names asso- names(v)[3] = ’myrandmatrix’
ment in a list. ciated with elements of cell arrays.) Use names(v) to see all names, and
names(v)=NULL to clear all names.
3 Computations
3.1 Basic computations
No. Description Matlab R
48 a + b, a − b, ab, a/b a+b, a-b, a*b, a/b a+b, a-b, a*b, a/b
√
49 a sqrt(a) sqrt(a)
50 ab a^b a^b
51 |a| (note: for complex ar- abs(a) abs(a)
guments, this computes the
modulus)
52 ea exp(a) exp(a)
53 ln(a) log(a) log(a)
54 log2 (a), log10 (a) log2(a), log10(a) log2(a), log10(a)
55 sin(a), cos(a), tan(a) sin(a), cos(a), tan(a) sin(a), cos(a), tan(a)
56 sin−1 (a), cos−1 (a), tan−1 (a) asin(a), acos(a), atan(a) asin(a), acos(a), atan(a)
57 sinh(a), cosh(a), tanh(a) sinh(a), cosh(a), tanh(a) sinh(a), cosh(a), tanh(a)
58 sinh−1 (a), cosh−1 (a), asinh(a), acosh(a), atanh(a) asinh(a), acosh(a), atanh(a)
−1
tanh (a)
D. Hiebeler, Matlab / R Reference 7
• Matlab and R both have a max function (and R has pmax and which.max as well) which behaves
in the same ways as min but to compute maxima rather than minima.
• Functions like exp, sin, sqrt etc. will operate on arrays in both Matlab and R, doing the
computations for each element of the matrix.
No. Description Matlab R
136 Number of rows in A size(A,1) nrow(A)
137 Number of columns in A size(A,2) ncol(A)
138 Dimensions of A, listed in a size(A) dim(A)
vector
139 Number of elements in vector length(v) length(v)
v
140 Total number of elements in numel(A) length(A)
matrix A
141 Max. dimension of A length(A) max(dim(A))
142 Sort values in vector v sort(v) sort(v)
143 Sort values in v, putting [s,idx]=sort(v) tmp=sort(v,index.return=TRUE);
sorted values in s, and indices s=tmp$x; idx=tmp$ix
in idx, in the sense that s[k]
= x[idx[k]]
144 Sort the order of the rows of sortrows(m) m[order(m[,1]),]
matrix m This sorts according to the first col- This only sorts according to the first
umn, then uses column 2 to break column. To use column 2 to break
ties, then column 3 for remaining ties, and then column 3 to break fur-
ties, etc. Complex numbers are ther ties, do
sorted by abs(x), and ties are then m[order(m[,1], m[,2], m[,3]),]
broken by angle(x). Complex numbers are sorted first by
real part, then by imaginary part.
145 Sort order of rows of matrix sortrows(m, [c1 c2 c2]) m[order(m[,c1], m[,c2],
m, specifying to use columns m[,c3]),]
c1, c2, c3 as the sorting
“keys”
D. Hiebeler, Matlab / R Reference 13
3.4 Root-finding
No. Description Matlab R
155 Find roots of polynomial roots(v) polyroot(rev(v)) (This function
whose coefficients are stored really wants the vector to have the
in vector v (coefficients in v constant coefficient first in v; rev re-
are highest-order first) verses their order to achieve this.)
156 Find zero (root) of a function Define function f(x), then do Define function f(x), then do
f (x) of one variable fzero(f,x0) to search for a root uniroot(f, c(a,b)) to find a root
near x0, or fzero(f,[a b]) to find between a and b, assuming the sign
a root between a and b, assuming of f (x) differs at x = a and x = b.
the sign of f (x) differs at x = a Default forward error tolerance (i.e.
and x = b. Default forward error error in x) is fourth root of machine
tolerance (i.e. error in x) is machine epsilon, (ǫmach )0.25 . To specify e.g.
epsilon ǫmach . a tolerance of 2−52 , do uniroot(f,
c(a,b), tol=2^-52).
160 Find values of x, y, z First write function f(v,p1,p2) First write function f(v,p1,p2) which
which minimize function which accepts a vector argument accepts a vector argument v contain-
f (x, y, z, p1 , p2 ), using a v containing values of x, y, and ing values of x, y, and z, along with
starting guess of x = 1, z, along with the extra parame- the extra parameters, and returns the
y = 2.2, and z = 3.4, where ters, and returns the scalar value scalar value f (x, y, z, p1 , p2 ), then do:
the function takes some extra f (x, y, z, p1 , p2 ), then do:
parameters (useful e.g. for optim(c(1,2.2,3.4), f, p1=p1,
doing things like nonlinear fminsearch(@f,[1 2.2 3.4], ... p2=p2)$par
least-squares optimization [ ], p1, p2)
where you pass in some data Or use an anonymous function:
vectors as extra parameters).
fminsearch(@(x) f(x,p1,p2), ...
[1 2.2 3.4])
D. Hiebeler, Matlab / R Reference 15
The return vector p has the coeffi- The return vector p has the coeffi-
cients in descending order, i.e. p(1) cients in ascending order, i.e. p[1] is
is c1 , and p(2) is c0 . c0 , and p[2] is c1 .
164 Fit the quadratic polynomial
y = c2 x2 + c1 x + c0 to data in p = polyfit(x,y,2) p = coef(lm(y ~ x + I(x^2)))
vectors x and y.
The return vector p has the coeffi- The return vector p has the coeffi-
cients in descending order, i.e. p(1) cients in ascending order, i.e. p[1] is
is c2 , p(2) is c1 , and p(3) is c0 . c0 , p[2] is c1 , and p[3] is c2 .
165 Fit nth degree polynomial There isn’t a simple function built
y = cn xn + cn−1 xn−1 + . . . + p = polyfit(x,y,n) into the standard R distribution to do
c1 x + c0 to data in vectors x this, but see the polyreg function in
and y. The return vector p has the coeffi- the mda package (see item 316 for
cients in descending order, p(1) is how to install/load packages).
cn , p(2) is cn−1 , etc.
166 Fit the quadratic polynomial (I don’t know a simple way do this
with zero intercept, y = in Matlab, other than to write a p=coef(lm(y ~ -1 + x + I(x^2)))
c2 x2 + c1 x to data in vectors function which computes the sum
x and y. of squared residuals and use fmin- The return vector p has the coeffi-
search on that function. There is cients in ascending order, i.e. p[1] is
likely an easy way to do it in the c1 , and p[2] is c2 .
Statistics Toolbox.)
167 Fit natural cubic spline pp=csape(x,y,’variational’); tmp=spline(x,y,method=’natural’,
(S ′′ (x) = 0 at both end- yy=ppval(pp,xx) but note that xout=xx); yy=tmp$y
points) to points (xi , yi ) csape is in Matlab’s Spline
whose coordinates are in Toolbox
vectors x and y; evaluate at
points whose x coordinates
are in vector xx, storing
corresponding y’s in yy
168 Fit cubic spline using I’m not aware of a function to do this tmp=spline(x,y,xout=xx);
Forsythe, Malcolm and in Matlab yy=tmp$y
Moler method (third deriva-
tives at endpoints match
third derivatives of exact cu-
bics through the four points
at each end) to points (xi , yi )
whose coordinates are in
vectors x and y; evaluate at
points whose x coordinates
are in vector xx, storing
corresponding y’s in yy
D. Hiebeler, Matlab / R Reference 17
for (i in v) command
for (i in v) {
command1
command2
}
D. Hiebeler, Matlab / R Reference 18
if (cond) command
If multiple commands:
if (cond) {
command1
command2
}
If multiple commands:
Note: Matlab also has an “elseif”
statement, e.g.: if (cond) {
command1
if cond1
command2
command1
} else {
elseif cond2
command3
command2
command4
elseif cond3
}
command3
else Warning: the “else” must be on the
command4 same line as command1 or the “}”
end (when typed interactively at the com-
mand prompt), otherwise R thinks the
“if” statement was finished and gives
an error.
R does not have an “elseif” state-
ment.
Logical comparisons which can be used on scalars in “if” statements, or which operate element-by-
element on vectors/matrices:
Matlab R Description
x<a x <a True if x is less than a
x>a x >a True if x is greater than a
x <= a x <= a True if x is less than or equal to a
x >= a x >= a True if x is greater than or equal to a
x == a x == a True if x is equal to a
x ~= a x != a True if x is not equal to a
D. Hiebeler, Matlab / R Reference 19
Scalar logical operators:
Description Matlab R
a AND b a && b a && b
a OR b a || b a || b
a XOR b xor(a,b) xor(a,b)
NOT a ~a !a
The && and || operators are short-circuiting, i.e. && stops as soon as any of its terms are FALSE, and
|| stops as soon as any of its terms are TRUE.
Description Matlab R
a AND b a & b a & b
a OR b a | b a | b
a XOR b xor(a,b) xor(a,b)
NOT a ~a !a
5 Functions, ODEs
No. Description Matlab R
182 Implement a function Put the following in add.m: Enter the following, or put it in a file
add(x,y) and source that file:
function retval=add(x,y)
retval = x+y; add = function(x,y) {
return(x+y)
}
Then you can do e.g. add(2,3)
Then you can do e.g. add(2,3).
Note, the curly brackets aren’t needed
if your function only has one line.
Also, the return keyword is optional
in the above example, as the value of
the last expression in a function gets
returned, so just x+y would work
too.
183 Implement a function Write function as follows: Write function as follows:
f(x,y,z) which returns mul-
tiple values, and store those function [a,b] = f(x,y,z) f = function(x,y,z) {
return values in variables u a = x*y+z; b=2*sin(x-z); a = x*y+z; b=2*sin(x-z)
and v return(list(a,b))
Then call the function by doing: }
[u,v] = f(2,8,12)
Then call the function by do-
ing: tmp=f(2,8,12); u=tmp[[1]];
v=tmp[[2]]. The above is most gen-
eral, and will work even when u and
v are different types of data. If they
are both scalars, the function could
simply return them packed in a vec-
tor, i.e. return(c(a,b)). If they
are vectors of the same size, the func-
tion could return them packed to-
gether into the columns of a matrix,
i.e. return(cbind(a,b)).
D. Hiebeler, Matlab / R Reference 22
Note that the “*rnd,” “*pdf,” and “*cdf” functions described below are all part of the Matlab
Statistics Toolbox, and not part of the core Matlab distribution.
No. Description Matlab R
202 Generate a random value binornd(n,p) rbinom(1,n,p)
from the binomial(n, p) dis-
tribution
203 Generate a random value poissrnd(lambda) rpois(1,lambda)
from the Poisson distribution
with parameter λ
204 Generate a random value exprnd(mu) or -mu*log(rand) will rexp(1, 1/mu)
from the exponential distri- work even without the Statistics
bution with mean µ Toolbox.
205 Generate a random value unidrnd(k) or floor(rand*k)+1 sample(k,1)
from the discrete uniform dis- will work even without the Statistics
tribution on integers 1 . . . k Toolbox.
206 Generate n iid random values unidrnd(k,n,1) or sample(k,n,replace=TRUE)
from the discrete uniform dis- floor(rand(n,1)*k)+1 will work
tribution on integers 1 . . . k even without the Statistics Toolbox.
207 Generate a random value unifrnd(a,b) or (b-a)*rand + a runif(1,a,b)
from the continuous uniform will work even without the Statistics
distribution on the interval Toolbox.
(a, b)
208 Generate a random value normrnd(mu,sigma) or rnorm(1,mu,sigma)
from the normal distribution mu + sigma*randn will work
with mean µ and standard even without the Statistics Toolbox.
deviation σ
209 Generate a random vector mnrnd(n,p) rmultinom(1,n,p)
from the multinomial distri-
bution, with n trials and
probability vector p
210 Generate j random vectors mnrnd(n,p,j) rmultinom(j,n,p)
from the multinomial distri- The vectors are returned as rows of The vectors are returned as columns
bution, with n trials and a matrix of a matrix
probability vector p
Notes:
• The Matlab “*rnd” functions above can all take additional r,c arguments to build an r × c matrix
of iid random values. E.g. poissrnd(3.5,4,7) for a 4 × 7 matrix of iid values from the Poisson
distribution with mean λ = 3.5. The unidrnd(k,n,1) command above is an example of this, to
generate a k × 1 column vector.
D. Hiebeler, Matlab / R Reference 25
• The first parameter of the R “r*” functions above specifies how many values are desired. E.g. to
generate 28 iid random values from a Poisson distribution with mean 3.5, use rpois(28,3.5). To
get a 4 × 7 matrix of such values, use matrix(rpois(28,3.5),4).
7 Graphics
7.1 Various types of plotting
No. Description Matlab R
224 Create a new figure window figure dev.new() Notes: internally, on Win-
dows this calls windows(), on MacOS
it calls quartz(), and on Linux it
calls x11(). x11() is also available
on MacOS. In R sometime after 2.7.0,
X11 graphics started doing antialising
by default, which makes plots look
smoother but takes longer to draw.
If you are using R on Linux (which
uses X11 graphics by default) or
X11 graphics on MacOS and notice
that figure plotting is extremely slow
(especially if making many plots),
do this before calling dev.new():
X11.options(type=’Xlib’) or
X11.options(antialias=’none’).
Or just use e.g. x11(type=’Xlib’)
to make new figure windows. They
are uglier (lines are more jagged), but
render much more quickly.
225 Select figure number n figure(n) (will create the figure if it dev.set(n) (returns the actual de-
doesn’t exist) vice selected; will be different from n
if there is no figure device with num-
ber n)
226 Determine which figure win- gcf dev.cur()
dow is currently active
227 List open figure windows get(0,’children’) (The 0 handle dev.list()
refers to the root graphics object.)
228 Close figure window(s) close to close the current figure win- dev.off() to close the currently ac-
dow, close(n) to close a specified tive figure device, dev.off(n) to close
figure, and close all to close all fig- a specified one, and graphics.off()
ures to close all figure devices.
229 Plot points using open circles plot(x,y,’o’) plot(x,y)
230 Plot points using solid lines plot(x,y) plot(x,y,type=’l’) (Note: that’s a
lower-case ’L’, not the number 1)
231 Plotting: color, point mark- plot(x,y,str) where str is a
ers, linestyle string specifying color, point marker, plot(x,y,type=str1,
and/or linestyle (see table below) pch=arg2,col=str3,
(e.g. ’gs--’ for green squares with lty=arg4)
dashed line)
You can then click on the small You can include shading in the im-
curved arrow in the figure window age via e.g. persp(A,shade=0.5).
(or choose “Rotate 3D” from the There are two viewing angles you
“Tools” menu), and then click and can also specify, among other pa-
drag the mouse in the figure to ro- rameters, e.g. persp(A, shade=0.5,
tate it in three dimensions. theta=50, phi=35).
242 Surface plot of f (x, y) =
√
sin(x + y) y for 100 values x = linspace(0,10,100); x = seq(0,10,len=100)
of x between 0 and 10, and y = linspace(2,8,90); y = seq(2,8,len=90)
90 values of y between 2 and [X,Y] = meshgrid(x,y); f = function(x,y)
8 Z = sin(X+Y).*sqrt(Y); return(sin(x+y)*sqrt(y))
surf(X,Y,Z) z = outer(x,y,f)
shading flat persp(x,y,z)
Matlab plotting specifications, for use with plot, fplot, semilogx, semilogy, loglog, etc:
Symbol Color Symbol Marker Symbol Linestyle
b blue . point (.) - solid line
g green o circle (◦) : dotted line
r red x cross (×) -. dash-dot line
c cyan + plus sign (+) -- dashed line
m magenta * asterisk (∗)
y yellow s square (¤)
k black d diamond (♦)
w white v triangle (down) (▽)
^ triangle (up) (△)
< triangle (left) (⊳)
> triangle (right) (⊲)
p pentragram star
h hexagram star
R plotting specifications for col (color), pch (plotting character), and type arguments, for use with plot,
matplot, points, and lines:
col Description pch Description type Description
’blue’ Blue ’a’ a (similarly for other p points
characters, but see ’.’
below for an exception
’green’ Green 19 solid circle l lines
’red’ Red 20 bullet (smaller circle) b both
’cyan’ Cyan 21 open circle c lines part only of “b”
’magenta’ Magenta 22 square o lines, points overplotted
’yellow’ Yellow 23 diamond h histogram-like lines
’black’ Black 24 triangle point-up s steps
’#RRGGBB’ hexadecimal specifica- 25 triangle point-down S another kind of steps
tion of Red, Green,
Blue
(Other names) See colors() for list of ’.’ rectangle of size 0.01 n no plotting
available color names. inch, 1 pixel, or 1 point
(1/72 inch) depending
on device
(See table on next page
for more)
D. Hiebeler, Matlab / R Reference 33
R plotting specifications for lty (line-type) argument, for use with plot, matplot, points, and lines:
lty Description
0 blank
1 solid
2 dashed
3 dotted
4 dotdash
5 longdash
6 twodash
24 25 A A b b . # #
18 19 20 21 22 23
12 13 14 15 16 17
6 7 8 9 10 11
0 1 2 3 4 5
R plotting characters, i.e. values for pch argument (from the book R Graphics, by Paul Murrell,
Chapman & Hall / CRC, 2006)
D. Hiebeler, Matlab / R Reference 34
9 Miscellaneous
9.1 Variables
No. Description Matlab R
274 Assigning to variables x = 5 x <- 5 or x = 5 Note: for compati-
bility with S-plus, many people prefer
the first form.
275 From within a function, as- assignin(’base’, ’y’, 7) y <<- 7
sign a value to variable y
in the base environment (i.e.
the command prompt envi-
ronment)
276 From within a function, ac- evalin(’base’, ’y’) get(’y’, envir=globalenv())
cess the value of variable y Though note that inside a function,
in the base environment (i.e. if there isn’t a local variable y, then
the command prompt envi- just the expression y will look for one
ronment) in the base environment, but if there
is a local y then that one will be used
instead.
277 Short list of defined variables who ls()
278 Long list of defined variables whos ls.str()
279 See detailed info about the whos ab str(ab)
variable ab
280 See detailed info about all whos *ab* ls.str(pattern=’ab’)
variables with “ab” in their
name
281 Open graphical data editor, openvar(A), or double-click on the fix(A)
to edit the value of variable variable in the Workspace pane (if
A (useful for editing values in it’s being displayed) of your Mat-
a matrix, though it works for labdesktop
non-matrix variables as well)
282 Clear one variable clear x rm(x)
283 Clear two variables clear x y rm(x,y)
284 Clear all variables clear all rm(list=ls())
285 See what type of object x is class(x) class(x)
286 (Variable names) Variable names must begin with a Variable names may contain letters,
letter, but after that they may con- digits, the period, and the underscore
tain any combination of letters, dig- character. They cannot begin with a
its, and the underscore character. digit or underscore, or with a period
Names are case-sensitive. followed by a digit. Names are case-
sensitive.
287 Result of last command ans contains the result of the last .Last.value contains the result of
command which did not assign its the last command, whether or not its
value to a variable. E.g. after 2+5; value was assigned to a variable. E.g.
x=3, then ans will contain 7. after 2+5; x=3, then .Last.value will
contain 3.
D. Hiebeler, Matlab / R Reference 39
10 Spatial Modeling
No. Description Matlab R
317 Take an L×L matrix A of A = (A | (rand(L) < p))*1; A = (A | (matrix(runif(L^2),L)
0s and 1s, and “seed” frac- < p))*1
tion p of the 0s (turn them
into 1s), not changing entries
which are already 1.
318 Take an L × L matrix A of 0s A = (A & (rand(L) < 1-p))*1; A = (A & (matrix(runif(L^2),L)
and 1s, and “kill” fraction p < 1-p))*1
of the 1s (turn them into 0s),
not changing the rest of the
entries
319 Do “wraparound” on a coor- mod(newx-1,L)+1 Note: for porta- ((newx-1) %% L) + 1 Note: for
dinate newx that you’ve al- bility with other languages such as portability with other languages such
ready calculated. You can C which handle MOD of negative as C which handle MOD of nega-
replace newx with x+dx if values differently, you may want to tive values differently, you may want
you want to do wraparound get in the habit of instead doing to get in the habit of instead doing
on an offset x coordinate. mod(newx-1+L,L)+1 ((newx-1+L)%%L) + 1
320 Randomly initialize a portion dx=ix2-ix1+1; dy=iy2-iy1+1; dx=ix2-ix1+1; dy=iy2-iy1+1;
of an array: set fraction p of A(iy1:iy2,ix1:ix2) = ... A[iy1:iy2,ix1:ix2] =
sites in rows iy1 through iy2 (rand(dy,dx) < p0)*1; (matrix(runif(dy*dx),dy) <
and columns ix1 through ix2 p0)*1
equal to 1 (and set the rest of
the sites in that block equal
to zero). Note: this assume
iy1 < iy2 and ix1 < ix2.
INDEX OF MATLAB COMMANDS AND CONCEPTS 43
’, 77 class, 285
,, 309 clear, 282–284
.*, 76 clf, 255
..., 288 clock, 306
./, 82 close, 228
.^, 86 colon, see :
/, 81 colorbar, 259
:, 12–14 colormap
;, 309 building your own, 261
=, 274 colormap, 260, 261
[, 6–8 column vector, 7
%, 291 comments, 291
&, 175, 176 complex numbers, 69–74
^, 50, 84, 85 cond, 96–98
\, 78, 83 conj, 72
{ 45 continue, 180
contour, 243
abs, 51, 70 conv, 154
acos, 56 corr, 110–115
acosh, 58 cos, 55
addpath, 313 cosh, 57
all, 177 cov, 108, 109
angle, 71 cputime, 305
annotation, 252, 253 csape, 167, 169, 170
ans, 287 cubic splines, 168, 169
any, 178 natural, 167
arrows in plots, 252, 253 not-a-knot, 171
asin, 56 periodic, 170
asinh, 58 cumprod, 124
assignin, 275 cumsum, 120–123
atan, 56 cumulative distribution functions
atanh, 58 binomial, 218
average, see mean continuous uniform on interval (a, b), 222
axis, 244 discrete uniform from 1..n, 223
exponential, 220
bar, 233, 235, 236
normal, 221
binocdf, 218
Poisson, 219
binopdf, 211
binornd, 202 debugging, 311
boolean tests diag, 22, 23
scalar, 175 diff, 126
vector, 176–178 differential equations, see ode45
break, 180 dir, 270
disp, 292, 293
cd, 269
doc, 4
ceil, 62
drawnow, 263, 267
cell, 44
cell arrays, 44 echelon form, see matrix
extracting elements of, 45 eig, 88
cellular automata animation, 267
chol, 92
INDEX OF MATLAB COMMANDS AND CONCEPTS 44
xlabel, 246–248
zeros, 17, 19
INDEX OF R COMMANDS AND CONCEPTS 48
warning, 308
which, 149–151
which.max, see which.min
which.min, 135
while, 179
windows, 224
wireframe, 243
write, 273
x11, 224