Matlab R Sintax guide

Embed Size (px)

DESCRIPTION

This guide presents the most important functions in Matlab and thier correspondent sintaxes in R language.

Citation preview

  • MATLAB R / R ReferenceMarch 3, 2009

    David HiebelerDept. of Mathematics and Statistics

    University of MaineOrono, ME 04469-5752

    http://www.math.umaine.edu/faculty/hiebeler

    I wrote the first version of this reference during the Spring 2007 semester, as I learned R while teachingmy course MAT400, Modeling & Simulation at the University of Maine. The course covers populationand epidemiological modeling, including deterministic and stochastic models in discrete and continuoustime, along with spatial models. Half of the class meetings are in a regular classroom, and half are ina computer lab where students work through modeling & simulation exercises. When I taught earlierversions of the course, it was based on Matlab only. In Spring 2007, some biology graduate students inthe class who had learned R in statistics courses asked if they could use R in my class as well, and I saidyes. 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, sothat I wouldnt forget it later. Some items took a huge amount of time searching for a simple way to dowhat I wanted, but at the end of the semester, I was pleasantly surprised that almost everything I doin Matlab had an equivalent in R. I was also inspired to do this after seeing the R for Octave Usersreference written by Robin Hankin. Ive continued to add to the document, with many additions basedon 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 atthe end, which should make it easy to look up a command you know in one of the languages and learnhow to do it in the other (or if youre 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 itemnumbers 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 usefulwill be appreciated. I hope all the time I spent on this will prove useful for others in addition to myselfand my students. Note that sometimes I dont necessarily do things in what you may consider the bestway in a particular language; I often tried to do things in a similar way in both languages. But if youbelieve you have a better way (either simpler, or more computationally efficient) to do something, feelfree to let me know.

    Acknowledgements: Thanks to Alan Cobo-Lewis and Isaac Michaud for correcting some errors;and Stephen Eglen, David Khabie-Zeitoune, Lee Pang, Manas A. Pathak, and Corey Yanofsky for con-tributions.

    Permission is granted to make and distribute verbatim copies of this manual provided this permissionnotice is preserved on all copies.

    Permission is granted to copy and distribute modified versions of this manual under the conditionsfor verbatim copying, provided that the entire resulting derived work is distributed under the terms of apermission 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 atranslation approved by the Free Software Foundation.

    Copyright c20072009 David Hiebeler

    1

  • D. Hiebeler, Matlab / R Reference 2

    Contents

    1 Online help 3

    2 Entering/building/indexing matrices 42.1 Cell arrays and lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62.2 Structs and data frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

    3 Computations 73.1 Basic computations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73.2 Complex numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73.3 Matrix/vector computations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83.4 Root-finding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133.5 Function optimization/minimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143.6 Numerical integration / quadrature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143.7 Curve fitting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

    4 Conditionals, control structure, loops 16

    5 Functions, ODEs 19

    6 Probability and random values 21

    7 Graphics 257.1 Various types of plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257.2 Printing/saving graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327.3 Animating cellular automata / lattice simulations . . . . . . . . . . . . . . . . . . . . . . . 33

    8 Working with files 34

    9 Miscellaneous 359.1 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359.2 Strings and Misc. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

    10 Spatial Modeling 39

    Index of MATLAB commands and concepts 40

    Index of R commands and concepts 44

  • D. Hiebeler, Matlab / R Reference 3

    1 Online help

    No. Description Matlab R1 Show help for a function (e.g.

    sqrt)help sqrt, or helpwin sqrt to seeit in a separate window

    help(sqrt) or ?sqrt

    2 Show help for a built-in key-word (e.g. for)

    help for help(for) or ?for

    3 General list of many help top-ics

    help library() to see available libraries,or library(help=base) for verylong list of stuff in base package whichyou can see help for

    4 Explore main documentationin browser

    doc or helpbrowser (previously itwas helpdesk, which is now beingphased out)

    help.start()

    5 Search documentation forkeyword or partial keyword(e.g. functions which refer tobinomial)

    lookfor binomial help.search(binomial)

  • D. Hiebeler, Matlab / R Reference 4

    2 Entering/building/indexing matrices

    No. Description Matlab R6 Enter a row vector ~v =[

    1 2 3 4] v=[1 2 3 4] v=c(1,2,3,4) or alternatively

    v=scan() then enter 1 2 3 4 andpress Enter twice (the blank lineterminates input)

    7 Enter a column vector

    1234

    [1; 2; 3; 4] c(1,2,3,4)

    (R does not distinguish between rowand column vectors.)

    8 Enter a matrix

    [1 2 34 5 6

    ][1 2 3 ; 4 5 6] To enter values by row:

    matrix(c(1,2,3,4,5,6), nrow=2,

    byrow=TRUE) To enter values bycolumn: 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

    AA(2,3) A[2,3]

    11 Access an element of matrixA using a single index: in-dices count down the first col-umn, then down the secondcolumn, etc.

    A(5) A[5]

    12 Build the vector [2 3 4 5 6 7] 2:7 2:713 Build the vector [7 6 5 4 3 2] 7:-1:2 7:214 Build the vector [2 5 8 11 14] 2:3:14 seq(2,14,3)15 Build a vector containing

    n equally-spaced values be-tween a and b inclusive

    linspace(a,b,n) seq(a,b,length.out=n) or justseq(a,b,len=n)

    16 Build a vector of length kcontaining all zeros

    zeros(k,1) (for a column vector) orzeros(1,k) (for a row vector)

    rep(0,k)

    17 Build a vector of length kcontaining the value j in allpositions

    j*ones(k,1) (for a column vector)or j*ones(1,k) (for a row vector)

    rep(j,k)

    18 Build anmn matrix of zeros zeros(m,n) matrix(0,nrow=m,ncol=n) or justmatrix(0,m,n)

    19 Build an m n matrix con-taining j in all positions

    j*ones(m,n) matrix(j,nrow=m,ncol=n) or justmatrix(j,m,n)

    20 n n identity matrix In eye(n) diag(n)21 Build diagonal matrix A us-

    ing elements of vector v as di-agonal entries

    diag(v) diag(v,nrow=length(v)) (Note: ifyou are sure the length of vector v is 2or more, you can simply say diag(v).)

    22 Extract diagonal elements ofmatrix A

    v=diag(A) v=diag(A)

    23 Glue two matrices a1 anda2 (with the same number ofrows) side-by-side

    [a1 a2] cbind(a1,a2)

    24 Stack two matrices a1 anda2 (with the same number ofcolumns) on top of each other

    [a1; a2] rbind(a1,a2)

  • D. Hiebeler, Matlab / R Reference 5

    No. Description Matlab R25 Reverse the order of elements

    in vector vv(end:-1:1) rev(v)

    26 Column 2 of matrix A A(:,2) A[,2] Note: that gives the result as avector. To make the result a m1 ma-trix instead, do A[,2,drop=FALSE]

    27 Row 7 of matrix A A(7,:) A[7,] Note: that gives the result as avector. To make the result a 1n ma-trix instead, do A[7,,drop=FALSE]

    28 All elements of A as a vector,column-by-column

    A(:) (gives a column vector) c(A)

    29 Rows 24, columns 610 of A(this is a 3 5 matrix)

    A(2:4,6:10) A[2:4,6:10]

    30 A 3 2 matrix consisting ofrows 7, 7, and 6 and columns2 and 1 of A (in that order)

    A([7 7 6], [2 1]) A[c(7,7,6),c(2,1)]

    31 Given a single index ind intoan m n matrix A, computethe row r and column c ofthat position (also works ifind is a vector)

    [r,c] = ind2sub(size(A), ind) r = ((ind-1) %% m) + 1

    c = floor((ind-1) / m) + 1

    32 Given the row r and columnc of an element of an m nmatrix A, compute the singleindex ind which can be usedto access that element of A(also works if r and c are vec-tors)

    ind = sub2ind(size(A), r, c) ind = (c-1)*m + r

    33 Given equal-sized vectors rand c (each of length k), setelements in rows (given by r)and columns (given by c) ofmatrix A equal to 12. Thatis, k elements of A will bemodified.

    inds = sub2ind(size(A),r,c);

    A(inds) = 12;

    inds = cbind(r,c)

    A[inds] = 12

    34 Truncate vector v, keepingonly the first 10 elements

    v = v(1:10) v = v[1:10], or length(v) = 10also works

    35 Reshape matrix A, making itan m n matrix with ele-ments taken columnwise fromthe original A (which musthave mn elements)

    A = reshape(A,m,n) dim(A) = c(m,n)

    36 Extract the lower-triangularportion of matrix A

    L = tril(A) L = A; L[upper.tri(L)]=0

    37 Extract the upper-triangularportion of matrix A

    U = triu(A) U = A; U[lower.tri(U)]=0

    38 Enter nn Hilbert matrix Hwhere Hij = 1/(i+ j 1)

    hilb(n) Hilbert(n), but this is part of theMatrix package which youll need toinstall (see item 295 for how to in-stall/load packages).

    39 Enter an n-dimensional array,e.g. a 342 array with thevalues 1 through 24

    reshape(1:24, 3, 4, 2) orreshape(1:24, [3 4 2])

    array(1:24, c(3,4,2)) (Note thata matrix is 2-D, i.e. rows andcolumns, while an array is more gen-erally N -D)

  • D. Hiebeler, Matlab / R Reference 6

    2.1 Cell arrays and lists

    No. Description Matlab R40 Build a vector v of length n,

    capable of containing differ-ent data types in different el-ements (called a cell array inMatlab, and a list in R)

    v = cell(1,n) In general,cell(m,n) makes an m n cellarray. Then you can do e.g.:

    v{1} = 12

    v{2} = hi there

    v{3} = rand(3)

    v = vector(list,n) Then youcan do e.g.:

    v[[1]] = 12

    v[[2]] = hi there

    v[[3]] = matrix(runif(9),3)

    41 Extract the ith element of acell/list vector v

    w = v{i}

    If you use regular indexing, i.e. w= v(i), then w will be a 1 1 cellmatrix containing the contents of theith element of v.

    w = v[[i]]

    If you use regular indexing, i.e. w =v[i], then w will be a list of length 1containing the contents of the ith ele-ment of v.

    42 Set the name of the ith ele-ment in a list.

    (Matlab does not have names asso-ciated with elements of cell arrays.)

    names(v)[3] = myrandmatrix

    Use names(v) to see all names, andnames(v)=NULL to clear all names.

    2.2 Structs and data frames

    No. Description Matlab R43 Create a matrix-like object

    with different named columns(a struct in Matlab, or adata frame in R)

    avals=2*ones(1,6);

    yvals=6:-1:1; v=[1 5 3 2 3 7];

    d=struct(a,avals,

    yy, yyvals, fac, v);

    v=c(1,5,3,2,3,7); d=data.frame(

    cbind(a=2, yy=6:1), v)

    Note that I (surprisingly) dont use R for statistics, and therefore have very little experience with dataframes (and also very little with Matlab structs). I will try to add more to this section later on.

  • D. Hiebeler, Matlab / R Reference 7

    3 Computations

    3.1 Basic computations

    No. Description Matlab R44 a+ b, a b, ab, a/b a+b, a-b, a*b, a/b a+b, a-b, a*b, a/b45

    a sqrt(a) sqrt(a)

    46 ab a^b a^b47 |a| (note: for complex ar-

    guments, this computes themodulus)

    abs(a) abs(a)

    48 ea exp(a) exp(a)49 ln(a) log(a) log(a)50 log2(a), log10(a) log2(a), log10(a) log2(a), log10(a)51 sin(a), cos(a), tan(a) sin(a), cos(a), tan(a) sin(a), cos(a), tan(a)

    52 sin1(a), cos1(a), tan1(a) asin(a), acos(a), atan(a) asin(a), acos(a), atan(a)53 sinh(a), cosh(a), tanh(a) sinh(a), cosh(a), tanh(a) sinh(a), cosh(a), tanh(a)

    54 sinh1(a), cosh1(a),tanh1(a)

    asinh(a), acosh(a), atanh(a) asinh(a), acosh(a), atanh(a)

    55 n MOD k (modulo arith-metic)

    mod(n,k) n %% k

    56 Round to nearest integer round(x) round(x) (Note: R uses IEC 60559standard, rounding 5 to the even digit so e.g. round(0.5) gives 0, not 1.)

    57 Round down to next lowestinteger

    floor(x) floor(x)

    58 Round up to next largest in-teger

    ceil(x) ceiling(x)

    59 Sign of x (+1, 0, or -1) sign(x) (Note: for complex values,this computes x/abs(x).)

    sign(x) (Does not work with com-plex values)

    60 Error function erf(x) =

    (2/) x0et

    2

    dt

    erf(x) 2*pnorm(x*sqrt(2))-1

    61 Complementary er-ror function cerf(x) =

    (2/)

    xet

    2

    dt = 1-erf(x)

    erfc(x) 2*pnorm(x*sqrt(2),lower=FALSE)

    62 Inverse error function erfinv(x) qnorm((1+x)/2)/sqrt(2)63 Inverse complementary error

    functionerfcinv(x) qnorm(x/2,lower=FALSE)/sqrt(2)

    Note: the various functions above (logarithm, exponential, trig, abs, and rounding functions) all workwith vectors and matrices, applying the function to each element, as well as with scalars.

    3.2 Complex numbers

    No. Description Matlab R64 Enter a complex number 1+2i 1+2i65 Modulus (magnitude) abs(z) abs(z) or Mod(z)66 Argument (angle) angle(z) Arg(z)67 Complex conjugate conj(z) Conj(z)68 Real part of z real(z) Re(z)69 Imaginary part of z imag(z) Im(z)

  • D. Hiebeler, Matlab / R Reference 8

    3.3 Matrix/vector computations

    No. Description Matlab R70 Matrix multiplication AB A * B A %*% B71 Element-by-element multipli-

    cation of A and BA .* B A * B

    72 Transpose of a matrix, AT A (This is actually the complex con-jugate (i.e. Hermitian) transpose;use A. for the non-conjugate trans-pose if you like; they are equivalentfor real matrices.)

    t(A) for transpose, or Conj(t(A)) forconjugate (Hermitian) transpose

    73 Solve A~x = ~b A\b Warning: if there is no solution,Matlab gives you a least-squaresbest fit. If there are many solu-tions, Matlab just gives you one ofthem.

    solve(A,b) Warning: this only workswith square invertible matrices.

    74 Reduced echelon form of A rref(A) R does not have a function to do this75 Compute inverse of A inv(A) solve(A)76 Compute AB1 A/B A %*% solve(B)77 Element-by-element division

    of A and BA ./ B A / B

    78 Compute A1B A\B solve(A,B)79 Square the matrix A A^2 A %*% A80 Raise matrix A to the kth

    powerA^k (No easy way to do this in R

    other than repeated multiplicationA %*% A %*% A...)

    81 Raise each element of A tothe kth power

    A.^k A^k

    82 Rank of matrix A rank(A) qr(A)$rank83 Set w to be a vector of eigen-

    values of A, and V a matrixcontaining the correspondingeigenvectors

    [V,D]=eig(A) and then w=diag(D)since Matlab returns the eigenval-ues on the diagonal of D

    tmp=eigen(A); w=tmp$values;

    V=tmp$vectors

    84 Permuted LU factorization ofa matrix

    [L,U,P]=lu(A) then the matricessatisfy PA = LU . Note that thisworks even with non-square matrices

    tmp=expand(lu(Matrix(A)));

    L=tmp$L; U=tmp$U; P=tmp$P thenthe matrices satisfy A = PLU , i.e.P1A = LU . Note that the lu andexpand functions are part of the Ma-trix package (see item 295 for how toinstall/load packages). Also note thatthis doesnt seem to work correctlywith non-square matrices. L, U, andP will be of class Matrix rather thanclass matrix; to make them the latter,instead do L=as.matrix(tmp$L),U=as.matrix(tmp$U), andP=as.matrix(tmp$P) above.

  • D. Hiebeler, Matlab / R Reference 9

    No. Description Matlab R85 Singular-value decomposi-

    tion: given m n matrixA with rank r, find m rmatrix P with orthonormalcolumns, diagonal r rmatrix S, and r n matrixQT with orthonormal rowsso that PSQT = A

    [P,S,Q]=svd(A,econ) tmp=svd(A); U=tmp$u; V=tmp$v;

    S=diag(tmp$d)

    86 Schur decomposi-tion of square matrix,A = QTQH = QTQ1 whereQ is unitary (i.e. QHQ = I)and T is upper triangular;QH = QT is the Hermitian(conjugate) transpose

    [Q,T]=schur(A) tmp=Schur(Matrix(A)); T=tmp@T;

    Q=tmp@Q Note that Schur is part ofthe Matrix package (see item 295 forhow to install/load packages). T andQ will be of class Matrix rather thanclass matrix; to make them the latter,instead do T=as.matrix(tmp@T) andQ=as.matrix(tmp@Q) above.

    87 Cholesky factorization of asquare, symmetric, positivedefinite matrix A = RTR,where R is upper-triangular

    R = chol(A) R = chol(A) Note that chol is partof the Matrix package (see item 295for how to install/load packages).

    88 QR factorization of matrix A,where Q is orthogonal (sat-isfying QQT = I) and R isupper-triangular

    [Q,R]=qr(A) satisfying QR = A, or[Q,R,E]=qr(A) to do permuted QRfactorization satisfying AE = QR

    z=qr(A); Q=qr.Q(z); R=qr.R(z);

    E=diag(n)[,z$pivot] (where n isthe number of columns in A) givespermuted QR factorization satisfyingAE = QR

    89 Vector norms norm(v,1) for 1-norm ~v1,norm(v,2) for Euclidean norm~v2, norm(v,inf) for infinity-norm~v, and norm(v,p) for p-norm~vp = (

    |vi|p)1/p

    R does not have a norm func-tion for vectors; only one formatrices. But the following willwork: norm(matrix(v),1) for1-norm ~v1, norm(matrix(v),i)for infinity-norm ~v, andsum(abs(v)^p)^(1/p) for p-norm

    ~vp = ( |vi|p)1/p

    90 Matrix norms norm(A,1) for 1-norm A1,norm(A) for 2-norm A2,norm(A,inf) for infinity-normA, and norm(A,fro) forFrobenius norm

    (i(A

    TA)ii)1/2

    norm(A,1) for 1-norm A1,max(svd(A)$d) for 2-norm A2,norm(A,i) for infinity-norm A,and norm(A,f) for Frobenius norm(

    i(ATA)ii

    )1/291 Condition number cond(A) =

    A1A11 of A, using 1-norm

    cond(A,1) (Note: Matlab also hasa function rcond(A) which computesreciprocal condition estimator usingthe 1-norm)

    1/rcond(A,1)

    92 Condition number cond(A) =A2A12 of A, using 2-norm

    cond(A,2) kappa(A, exact=TRUE) (leave outthe exact=TRUE for an esti-mate)

    93 Condition number cond(A) =AA1 of A, usinginfinity-norm

    cond(A,inf) 1/rcond(A,I)

  • D. Hiebeler, Matlab / R Reference 10

    No. Description Matlab R94 Compute mean of all ele-

    ments in vector or matrixmean(v) for vectors, mean(A(:)) formatrices

    mean(v) or mean(A)

    95 Compute means of columnsof a matrix

    mean(A) colMeans(A)

    96 Compute means of rows of amatrix

    mean(A,2) rowMeans(A)

    97 Compute standard deviationof all elements in vector ormatrix

    std(v) for vectors, std(A(:)) formatrices. This normalizes by n 1.Use std(v,1) to normalize by n.

    sd(v) for vectors, sd(c(A)) for ma-trices. This normalizes by n 1.

    98 Compute standard deviationsof columns of a matrix

    std(A). This normalizes by n 1.Use std(A,1) to normalize by n

    sd(A). This normalizes by n 1.

    99 Compute standard deviationsof rows of a matrix

    std(A,0,2) to normalize by n 1,std(A,1,2) to normalize by n

    apply(A,1,sd). This normalizes byn 1.

    100 Compute variance of all ele-ments in vector or matrix

    var(v) for vectors, var(A(:)) formatrices. This normalizes by n 1.Use var(v,1) to normalize by n.

    var(v) for vectors, var(c(A)) formatrices. This normalizes by n 1.

    101 Compute variance of columnsof a matrix

    var(A). This normalizes by n 1.Use var(A,1) to normalize by n

    apply(A,2,var). This normalizes byn 1.

    102 Compute variance of rows ofa matrix

    var(A,0,2) to normalize by n 1,var(A,1,2) to normalize by n

    apply(A,1,var). This normalizes byn 1.

    103 Compute covariance for twovectors of observations

    cov(v,w) computes the 2 2 co-variance matrix; the off-diagonal ele-ments give the desired covariance

    cov(v,w)

    104 Compute covariance matrix,giving covariances betweencolumns of matrix A

    cov(A) var(A) or cov(A)

    105 Given matrices A and B,build covariance matrix Cwhere cij is the covariance be-tween column i of A and col-umn j of B

    I dont know of a direct way todo this in Matlab. But one way is[Y,X]=meshgrid(std(B),std(A));

    X.*Y.*corr(A,B)

    cov(A,B)

    106 Compute Pearsons linearcorrelation coefficient be-tween elements of vectors vand w

    corr(v,w) Note: v and w mustbe column vectors. To make itwork regardless of whether theyare row or column vectors, docorr(v(:),w(:))

    cor(v,w)

    107 Compute Kendalls tau corre-lation statistic for vectors vand w

    corr(v,w,type,kendall) cor(v,w,method=kendall)

    108 Compute Spearmans rhocorrelation statistic forvectors v and w

    corr(v,w,type,spearman) cor(v,w,method=spearman)

    109 Compute pairwise Pearsonscorrelation coefficient be-tween columns of matrixA

    corr(A) The type argument mayalso be used as in the previous twoitems

    cor(A) The method argument mayalso be used as in the previous twoitems

    110 Compute matrix C of pair-wise Pearsons correlation co-efficients between each pair ofcolumns of matrices A and B,i.e. so cij is the correlationbetween column i of A andcolumn j of B

    corr(A,B) The type argumentmay also be used as just above

    cor(A,B) The method argumentmay also be used as just above

  • D. Hiebeler, Matlab / R Reference 11

    No. Description Matlab R111 Compute sum of all elements

    in vector or matrixsum(v) for vectors, sum(A(:)) formatrices

    sum(v) or sum(A)

    112 Compute sums of columns ofmatrix

    sum(A) colSums(A)

    113 Compute sums of rows of ma-trix

    sum(A,2) rowSums(A)

    114 Compute matrix exponentialeA =

    k=0 Ak/k!

    expm(A) expm(Matrix(A)), but this is part ofthe Matrix package which youll needto install (see item 295 for how to in-stall/load packages).

    115 Compute cumulative sum ofvalues in vector

    cumsum(v) cumsum(v)

    116 Compute cumulative sums ofcolumns of matrix

    cumsum(A) apply(A,2,cumsum)

    117 Compute cumulative sums ofrows of matrix

    cumsum(A,2) t(apply(A,1,cumsum))

    118 Compute cumulative sumof all elements of matrix(column-by-column)

    cumsum(A(:)) cumsum(A)

    119 Cumulative product of ele-ments in vector v

    cumprod(v) (Can also be used in thevarious ways cumsum can)

    cumprod(v) (Can also be used in thevarious ways cumsum can)

    120 Cumulative minimum ormaximum of elements invector v

    I dont know of an easy way to dothis in Matlab

    cummin(v) or cummax(v)

    121 Compute differences betweenconsecutive elements of vec-tor v. Result is a vectorw 1 element shorter than v,where element i of w is ele-ment i+1 of v minus elementi of v

    diff(v) diff(v)

    122 Make a vector y the same sizeas vector x, which equals 4everywhere that x is greaterthan 5, and equals 3 every-where else (done via a vector-ized computation).

    z = [3 4]; y = z((x > 5)+1) y = ifelse(x > 5, 4, 3)

    123 Compute minimum of valuesin vector v

    min(v) min(v)

  • D. Hiebeler, Matlab / R Reference 12

    No. Description Matlab R124 Compute minimum of all val-

    ues in matrix Amin(A(:)) min(A)

    125 Compute minimum value ofeach column of matrix A

    min(A) (returns a row vector) apply(A,2,min) (returns a vector)

    126 Compute minimum value ofeach row of matrix A

    min(A, [ ], 2) (returns a columnvector)

    apply(A,1,min) (returns a vector)

    127 Given matrices A and B,compute a matrix where eachelement is the minimum ofthe corresponding elements ofA and B

    min(A,B) pmin(A,B)

    128 Given matrix A and scalarc, compute a matrix whereeach element is the minimumof c and the corresponding el-ement of A

    min(A,c) pmin(A,c)

    129 Find minimum among all val-ues in matrices A and B

    min([A(:) ; B(:)]) min(A,B)

    130 Find index of the first timemin(v) appears in v, andstore that index in ind

    [y,ind] = min(v) ind = which.min(v)

    Notes:

    Matlab and R both have a max function (and R has pmax and which.max as well) which behavesin 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 thecomputations for each element of the matrix.

    No. Description Matlab R131 Number of rows in A size(A,1) nrow(A)132 Number of columns in A size(A,2) ncol(A)133 Dimensions of A, listed in a

    vectorsize(A) dim(A)

    134 Number of elements in vectorv

    length(v) length(v)

    135 Total number of elements inmatrix A

    numel(A) length(A)

    136 Max. dimension of A length(A) max(dim(A))137 Sort values in vector v sort(v) sort(v)138 Sort values in v, putting

    sorted values in s, and indicesin idx, in the sense that s[k]= x[idx[k]]

    [s,idx]=sort(v) tmp=sort(v,index.return=TRUE);

    s=tmp$x; idx=tmp$ix

    139 To count how many values inthe vector x are between 4and 7 (inclusive on the upperend)

    sum((x > 4) & (x 4) & (x 5) which(v > 5)

  • D. Hiebeler, Matlab / R Reference 13

    No. Description Matlab R141 Given matrix A, return list

    of indices of elements of Awhich are greater than 5, us-ing single-indexing

    find(A > 5) which(A > 5)

    142 Given matrix A, generatevectors r and c giving rowsand columns of elements of Awhich are greater than 5

    [r,c] = find(A > 5) w = which(A > 5, arr.ind=TRUE);

    r=w[,1]; c=w[,2]

    143 Given vector x (of presum-ably discrete values), build avector v listing unique val-ues in x, and correspondingvector c indicating how manytimes those values appear inx

    v = unique(x); c = hist(x,v); w=table(x); c=as.numeric(w);

    v=as.numeric(names(w))

    144 Given vector x (of presum-ably continuous values), di-vide the range of values into kequally-sized bins, and builda vector m containing themidpoints of the bins and acorresponding vector c con-taining the counts of values inthe bins

    [c,m] = hist(x,k) w=hist(x,seq(min(x),max(x),

    length.out=k+1), plot=FALSE);

    m=w$mids; c=w$counts

    145 Convolution / polynomialmultiplication (given vectorsx and y containing polyno-mial coefficients, their convo-lution is a vector containingcoefficients of the product ofthe two polynomials)

    conv(x,y) convolve(x,rev(y),type=open)

    Note: the accuracy of this is notas good as Matlab; e.g. doingv=c(1,-1); for (i in 2:20)

    v=convolve(v,c(-i,1),

    type=open) to generate the20th-degree Wilkinson polynomialW (x) =

    20i=1(xi) gives a coefficient

    of 780.19 for x19, rather than thecorrect value -210.

    3.4 Root-finding

    No. Description Matlab R146 Find roots of polynomial

    whose coefficients are storedin vector v (coefficients in vare highest-order first)

    roots(v) polyroot(rev(v)) (This functionreally wants the vector to have theconstant coefficient first in v; rev re-verses their order to achieve this.)

    147 Find zero (root) of a functionf(x) of one variable

    Define function f(x), then dofzero(f,x0) to search for a rootnear x0, or fzero(f,[a b]) to finda root between a and b, assumingthe sign of f(x) differs at x = aand x = b. Default forward errortolerance (i.e. error in x) is machineepsilon mach.

    Define function f(x), then douniroot(f, c(a,b)) to find a rootbetween a and b, assuming the signof f(x) differs at x = a and x = b.Default forward error tolerance (i.e.error in x) is fourth root of machineepsilon, (mach)

    0.25. To specify e.g.a tolerance of 252, do uniroot(f,c(a,b), tol=2^-52).

  • D. Hiebeler, Matlab / R Reference 14

    3.5 Function optimization/minimization

    No. Description Matlab R148 Find value m which mini-

    mizes a function f(x) of onevariable within the intervalfrom a to b

    Define function f(x), then do

    m = fminbnd(f, a, b)

    Define function f(x), then do

    m = optimize(f,c(a,b))$minimum

    149 Find value m which mini-mizes a function f(x, p1, p2)with given extra parameters(but minimization is only oc-curing over the first argu-ment), in the interval from ato b.

    Define function f(x,p1,p2), then usean anonymous function:

    % first define values for p1

    % and p2, and then do:

    m=fminbnd(@(x) f(x,p1,p2),a,b)

    Define function f(x,p1,p2), then:

    # first define values for p1

    # and p2, and then do:

    m = optimize(f, c(a,b), p1=p1,

    p2=p2)$minimum

    150 Find values of x, y, z whichminimize function f(x, y, z),using a starting guess of x =1, y = 2.2, and z = 3.4.

    First write function f(v) which ac-cepts a vector argument v containingvalues of x, y, and z, and returns thescalar value f(x, y, z), then do:

    fminsearch(@f,[1 2.2 3.4])

    First write function f(v) which ac-cepts a vector argument v containingvalues of x, y, and z, and returns thescalar value f(x, y, z), then do:

    optim(c(1,2.2,3.4),f)$par

    151 Find values of x, y, zwhich minimize functionf(x, y, z, p1, p2), using astarting guess of x = 1,y = 2.2, and z = 3.4, wherethe function takes some extraparameters (useful e.g. fordoing things like nonlinearleast-squares optimizationwhere you pass in some datavectors as extra parameters).

    First write function f(v,p1,p2)which accepts a vector argumentv containing values of x, y, andz, along with the extra parame-ters, and returns the scalar valuef(x, y, z, p1, p2), then do:

    fminsearch(@f,[1 2.2 3.4], ...

    [ ], p1, p2)

    Or use an anonymous function:

    fminsearch(@(x) f(x,p1,p2), ...

    [1 2.2 3.4])

    First write function f(v,p1,p2) whichaccepts a vector argument v contain-ing values of x, y, and z, along withthe extra parameters, and returns thescalar value f(x, y, z, p1, p2), then do:

    optim(c(1,2.2,3.4), f, p1=p1,

    p2=p2)$par

    3.6 Numerical integration / quadrature

    No. Description Matlab R152 Numerically integrate func-

    tion f(x) over interval froma to b

    quad(f,a,b) uses adaptive Simp-sons quadrature, with a defaultabsolute tolerance of 106. Tospecify absolute tolerance, usequad(f,a,b,tol)

    integrate(f,a,b) uses adaptivequadrature with default absoluteand relative error tolerances beingthe fourth root of machine epsilon,(mach)

    0.25 1.22 104. Tol-erances can be specified by usingintegrate(f,a,b, rel.tol=tol1,

    abs.tol=tol2). Note that the func-tion f must be written to work evenwhen given a vector of x values as itsargument.

  • D. Hiebeler, Matlab / R Reference 15

    3.7 Curve fitting

    No. Description Matlab R153 Fit the line y = c1x + c0 to

    data in vectors x and y.p = polyfit(x,y,1)

    The return vector p has the coeffi-cients in descending order, i.e. p(1)is c1, and p(2) is c0.

    p = coef(lm(y ~ x))

    The return vector p has the coeffi-cients in ascending order, i.e. p[1] isc0, and p[2] is c1.

    154 Fit the quadratic polynomialy = c2x

    2 + c1x+ c0 to data invectors x and y.

    p = polyfit(x,y,2)

    The return vector p has the coeffi-cients in descending order, i.e. p(1)is c2, p(2) is c1, and p(3) is c0.

    p = coef(lm(y ~ x + I(x^2)))

    The return vector p has the coeffi-cients in ascending order, i.e. p[1] isc0, p[2] is c1, and p[3] is c2.

    155 Fit nth degree polynomialy = cnx

    n + cn1xn1 + . . .+

    c1x + c0 to data in vectors xand y.

    p = polyfit(x,y,n)

    The return vector p has the coeffi-cients in descending order, p(1) iscn, p(2) is cn1, etc.

    There isnt a simple function builtinto the standard R distribution to dothis, but see the polyreg function inthe mda package (see item 295 forhow to install/load packages).

    156 Fit the quadratic polynomialwith zero intercept, y =c2x

    2 + c1x to data in vectorsx and y.

    (I dont know a simple way do thisin Matlab, other than to write afunction which computes the sumof squared residuals and use fmin-search on that function. There islikely an easy way to do it in theStatistics Toolbox.)

    p=coef(lm(y ~ -1 + x + I(x^2)))

    The return vector p has the coeffi-cients in ascending order, i.e. p[1] isc1, and p[2] is c2.

    157 Fit natural cubic spline(S(x) = 0 at both end-points) to points (xi, yi)whose coordinates are invectors x and y; evaluate atpoints whose x coordinatesare in vector xx, storingcorresponding ys in yy

    pp=csape(x,y,variational);

    yy=ppval(pp,xx) but note thatcsape is in Matlabs SplineToolbox

    tmp=spline(x,y,method=natural,

    xout=xx); yy=tmp$y

    158 Fit cubic spline usingForsythe, Malcolm andMoler method (third deriva-tives at endpoints matchthird derivatives of exact cu-bics through the four pointsat each end) to points (xi, yi)whose coordinates are invectors x and y; evaluate atpoints whose x coordinatesare in vector xx, storingcorresponding ys in yy

    Im not aware of a function to do thisin Matlab

    tmp=spline(x,y,xout=xx);

    yy=tmp$y

  • D. Hiebeler, Matlab / R Reference 16

    No. Description Matlab R159 Fit cubic spline such that

    first derivatives at endpointsmatch first derivatives of ex-act cubics through the fourpoints at each end) to points(xi, yi) whose coordinates arein vectors x and y; evaluateat points whose x coordinatesare in vector xx, storing cor-responding ys in yy

    pp=csape(x,y); yy=ppval(pp,xx)

    but csape is in Matlabs SplineToolbox

    Im not aware of a function to do thisin R

    160 Fit cubic spline with periodicboundaries, i.e. so that firstand second derivatives matchat the left and right ends(the first and last y valuesof the provided data shouldalso agree), to points (xi, yi)whose coordinates are in vec-tors x and y; evaluate atpoints whose x coordinatesare in vector xx, storing cor-responding ys in yy

    pp=csape(x,y,periodic);

    yy=ppval(pp,xx) but csape is inMatlabs Spline Toolbox

    tmp=spline(x,y,method=

    periodic, xout=xx); yy=tmp$y

    161 Fit cubic spline with not-a-knot conditions (the firsttwo piecewise cubics coincide,as do the last two), to points(xi, yi) whose coordinates arein vectors x and y; evaluateat points whose x coordinatesare in vector xx, storing cor-responding ys in yy

    yy=spline(x,y,xx) Im not aware of a function to do thisin R

    4 Conditionals, control structure, loops

    No. Description Matlab R162 for loops over values in a

    vector v (the vector v is of-ten constructed via a:b)

    for i=v

    command1

    command2

    end

    If only one command inside the loop:

    for (i in v)

    command

    or

    for (i in v) command

    If multiple commands inside the loop:

    for (i in v) {

    command1

    command2

    }

  • D. Hiebeler, Matlab / R Reference 17

    No. Description Matlab R163 if statements with no else

    clause if condcommand1

    command2

    end

    If only one command inside the clause:

    if (cond)

    command

    or

    if (cond) command

    If multiple commands:

    if (cond) {

    command1

    command2

    }

    164 if/else statement

    if cond

    command1

    command2

    else

    command3

    command4

    end

    Note: Matlab also has an elseifstatement, e.g.:

    if cond1

    command1

    elseif cond2

    command2

    elseif cond3

    command3

    else

    command4

    end

    If one command in clauses:

    if (cond)

    command1 else

    command2

    or

    if (cond) cmd1 else cmd2

    If multiple commands:

    if (cond) {

    command1

    command2

    } else {

    command3

    command4

    }

    Warning: the else must be on thesame line as command1 or the }(when typed interactively at the com-mand prompt), otherwise R thinks theif statement was finished and givesan 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 Descriptionx < a x < a True if x is less than ax > a x > a True if x is greater than ax = a True if x is greater than or equal to ax == a x == a True if x is equal to ax ~= a x != a True if x is not equal to a

  • D. Hiebeler, Matlab / R Reference 18

    Scalar logical operators:

    Description Matlab Ra AND b a && b a && ba OR b a || b a || ba 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.

    Matrix logical operators (they operate element-by-element):

    Description Matlab Ra AND b a & b a & ba OR b a | b a | ba XOR b xor(a,b) xor(a,b)NOT a ~a !a

    No. Description Matlab R165 To test whether a scalar value

    x is between 4 and 7 (inclu-sive on the upper end)

    if ((x > 4) && (x 4) && (x 4) & (x 4) & (x

  • D. Hiebeler, Matlab / R Reference 19

    No. Description Matlab R170 Switch statements for inte-

    gersswitch (x)

    case 10

    disp(ten)

    case {12,13}

    disp(dozen (bakers?))

    otherwise

    disp(unrecognized)

    end

    R doesnt have a switch statement ca-pable of doing this. It has a functionwhich is fairly limited for integers, butcan which do string matching. See?switch for more. But a basic ex-ample of what it can do for integers isbelow, showing that you can use it toreturn different expressions based onwhether a value is 1, 2, . . ..

    mystr = switch(x, one,

    two, three)

    print(mystr)

    Note that switch returns NULL if x islarger than 3 in the above case. Also,continuous values of x will be trun-cated to integers.

    5 Functions, ODEs

    No. Description Matlab R171 Implement a function

    add(x,y)Put the following in add.m:

    function retval=add(x,y)

    retval = x+y;

    Then you can do e.g. add(2,3)

    Enter the following, or put it in a fileand source that file:

    add = function(x,y) {

    return(x+y)

    }

    Then you can do e.g. add(2,3).Note, the curly brackets arent neededif your function only has one line.

    172 Implement a functionf(x,y,z) which returns mul-tiple values, and store thosereturn values in variables uand v

    Write function as follows:

    function [a,b] = f(x,y,z)

    a = x*y+z; b=2*sin(x-z);

    Then call the function by doing:[u,v] = f(2,8,12)

    Write function as follows:

    f = function(x,y,z) {

    a = x*y+z; b=2*sin(x-z)

    return(list(a,b))

    }

    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 andv are different types of data. If theyare both scalars, the function couldsimply return them packed in a vec-tor, i.e. return(c(a,b)). If theyare 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 20

    No. Description Matlab R173 Numerically solve ODE

    dx/dt = 5x from t = 3 tot = 12 with initial conditionx(3) = 7

    First implement function

    function retval=f(t,x)

    retval = 5*x;

    Then do ode45(@f,[3,12],7)to plot solution, or[t,x]=ode45(@f,[3,12],7) to getback vector t containing time valuesand vector x containing correspond-ing function values. If you wantfunction values at specific times,e.g. 3, 3.1, 3.2, . . . , 11.9, 12, you cando [t,x]=ode45(@f,3:0.1:12,7).Note: in older versions of Matlab,use f instead of @f.

    First implement function

    f = function(t,x,parms) {

    return(list(5*x))

    }

    Then do y=lsoda(7, seq(3,12,0.1), f,NA) to obtain solutionvalues at times 3, 3.1, 3.2, . . . , 11.9, 12.The first column of y, namely y[,1]contains the time values; the secondcolumn y[,2] contains the corre-sponding function values. Note:lsoda is part of the deSolve package(see item 295 for how to install/loadpackages).

    174 Numerically solve system ofODEs dw/dt = 5w, dz/dt =3w + 7z from t = 3 to t = 12with initial conditions w(3) =7, z(3) = 8.2

    First implement function

    function retval=myfunc(t,x)

    w = x(1); z = x(2);

    retval = zeros(2,1);

    retval(1) = 5*w;

    retval(2) = 3*w + 7*z;

    Then doode45(@myfunc,[3,12],[7;

    8.2]) to plot solution, or[t,x]=ode45(@myfunc,[3,12],[7;

    8.2]) to get back vector t contain-ing time values and matrix x, whosefirst column containing correspond-ing w(t) values and second columncontains z(t) values. If you wantfunction values at specific times, e.g.3, 3.1, 3.2, . . . , 11.9, 12, you can do[t,x]=ode45(@myfunc,3:0.1:12,[7;

    8.2]). Note: in older versions ofMatlab, use f instead of @f.

    First implement function

    myfunc = function(t,x,parms) {

    w = x[1]; z = x[2];

    return(list(c(5*w, 3*w+7*z)))

    }

    Then do y=lsoda(c(7,8.2),seq(3,12, 0.1), myfunc,NA)

    to obtain solution values at times3, 3.1, 3.2, . . . , 11.9, 12. The firstcolumn of y, namely y[,1] containsthe time values; the second columny[,2] contains the correspondingvalues of w(t); and the third columncontains z(t). Note: lsoda is part ofthe deSolve package (see item 295for how to install/load packages).

    175 Pass parameters such as r =1.3 and K = 50 to an ODEfunction from the commandline, solving dx/dt = rx(1 x/K) from t = 0 to t = 20with initial condition x(0) =2.5.

    First implement function

    function retval=func2(t,x,r,K)

    retval = r*x*(1-x/K)

    Then do ode45(@func2,[0 20],2.5, [ ], 1.3, 50). The emptymatrix is necessary between the ini-tial condition and the beginning ofyour extra parameters.

    First implement function

    func2=function(t,x,parms) {

    r=parms[1]; K=parms[2]

    return(list(r*x*(1-x/K)))

    }

    Then do

    y=lsoda(2.5,seq(0,20,0.1)

    func2,c(1.3,50))

    Note: lsoda is part of the deSolvepackage (see item 295 for how to in-stall/load packages).

  • D. Hiebeler, Matlab / R Reference 21

    6 Probability and random values

    No. Description Matlab R176 Generate a continuous uni-

    form random value between 0and 1

    rand runif(1)

    177 Generate vector of n uniformrandom vals between 0 and 1

    rand(n,1) or rand(1,n) runif(n)

    178 Generate mn matrix of uni-form random values between0 and 1

    rand(m,n) matrix(runif(m*n),m,n) or justmatrix(runif(m*n),m)

    179 Generate mn matrix of con-tinuous uniform random val-ues between a and b

    a+rand(m,n)*(b-a) or if youhave the Statistics toolbox thenunifrnd(a,b,m,n)

    matrix(runif(m*n,a,b),m)

    180 Generate a random integerbetween 1 and k

    floor(k*rand) + 1 floor(k*runif(1)) + 1 Note:sample(k)[1] would also work, but Ibelieve in general will be less efficient,because that actually generates manyrandom numbers and then just usesone of them.

    181 Generate mn matrix of dis-crete uniform random inte-gers between 1 and k

    floor(k*rand(m,n))+1 or if youhave the Statistics toolbox thenunidrnd(k,m,n)

    floor(k*matrix(runif(m*n),m))+1

    182 Generate mn matrix whereeach entry is 1 with probabil-ity p, otherwise is 0

    (rand(m,n)

  • D. Hiebeler, Matlab / R Reference 22

    No. Description Matlab R188 Choose k values (with re-

    placement) from the vector v,storing result in w

    L=length(v);

    w=v(floor(L*rand(k,1))+1) Or,if you have the Statistics Toolbox,w=randsample(v,k,replace=true)

    w=sample(v,k,replace=TRUE)

    189 Choose k values (without re-placement) from the vector v,storing result in w

    L=length(v); ri=randperm(L);

    ri=ri(1:k); w=v(ri) Or, ifyou have the Statistics Toolbox,w=randsample(v,k,replace=false)

    w=sample(v,k,replace=FALSE)

    190 Set the random-number gen-erator back to a known state(useful to do at the beginningof a stochastic simulationwhen debugging, so youll getthe same sequence of randomnumbers each time)

    rand(state, 12) set.seed(12)

    Note that the *rnd, *pdf, and *cdf functions described below are all part of the MatlabStatistics Toolbox, and not part of the core Matlab distribution.

    No. Description Matlab R191 Generate a random value

    from the Binomial(n, p) dis-tribution

    binornd(n,p) rbinom(1,n,p)

    192 Generate a random valuefrom the Poisson distributionwith parameter

    poissrnd(lambda) rpois(1,lambda)

    193 Generate a random valuefrom the Exponential distri-bution with mean

    exprnd(mu) or -mu*log(rand) willwork even without the StatisticsToolbox.

    rexp(1, 1/mu)

    194 Generate a random valuefrom the discrete uniform dis-tribution on integers 1 . . . k

    unidrnd(k) or floor(rand*k)+1will work even without the StatisticsToolbox.

    sample(k,1)

    195 Generate n iid random valuesfrom the discrete uniform dis-tribution on integers 1 . . . k

    unidrnd(k,n,1) orfloor(rand(n,1)*k)+1 will workeven without the Statistics Toolbox.

    sample(k,n,replace=TRUE)

    196 Generate a random valuefrom the continuous uniformdistribution on the interval(a, b)

    unifrnd(a,b) or (b-a)*rand + awill work even without the StatisticsToolbox.

    runif(1,a,b)

    197 Generate a random valuefrom the normal distributionwith mean mu and standarddeviation

    normrnd(mu,sigma) ormu + sigma*randn will workeven without the Statistics Toolbox.

    rnorm(1,mu,sigma)

    Notes:

    The Matlab *rnd functions above can all take additional r,c arguments to build an r c matrixof iid random values. E.g. poissrnd(3.5,4,7) for a 4 7 matrix of iid values from the Poissondistribution with mean = 3.5. The unidrnd(n,k,1) command above is an example of this, togenerate a k 1 column vector.

    The first parameter of the R r* functions above specifies how many values are desired. E.g. togenerate 28 iid random values from a Poisson distribution with mean 3.5, use rpois(28,3.5). Toget a 4 7 matrix of such values, use matrix(rpois(28,3.5),4).

  • D. Hiebeler, Matlab / R Reference 23

    No. Description Matlab R198 Compute probability that

    a random variable from theBinomial(n, p) distributionhas value x (i.e. the density,or pdf).

    binopdf(x,n,p) ornchoosek(n,x)*p^x*(1-p)^(n-x)

    will work even without the StatisticsToolbox, as long as n and x arenon-negative integers and 0 p 1.

    dbinom(x,n,p)

    199 Compute probability that arandom variable from thePoisson() distribution hasvalue x.

    poisspdf(x,lambda) orexp(-lambda)*lambda^x /

    factorial(x) will work evenwithout the Statistics Toolbox, aslong as x is a non-negative integerand lambda 0.

    dpois(x,lambda)

    200 Compute probability densityfunction at x for a randomvariable from the exponentialdistribution with mean .

    exppdf(x,mu) or(x>=0)*exp(-x/mu)/mu will workeven without the Statistics Toolbox,as long as mu is positive.

    dexp(x,1/mu)

    201 Compute probability densityfunction at x for a randomvariable from the Normal dis-tribution with mean andstandard deviation .

    normpdf(x,mu,sigma) orexp(-(x-mu)^2/(2*sigma^2))/

    (sqrt(2*pi)*sigma) will work evenwithout the Statistics Toolbox.

    dnorm(x,mu,sigma)

    202 Compute probability densityfunction at x for a randomvariable from the continuousuniform distribution on inter-val (a, b).

    unifpdf(x,a,b) or((x>=a)&&(x=1)&&(x= 1) &&

    (x

  • D. Hiebeler, Matlab / R Reference 24

    The corresponding CDF functions are below:No. Description Matlab R204 Compute probability that a

    random variable from theBinomial(n, p) distribution isless than or equal to x (i.e.the cumulative distributionfunction, or cdf).

    binocdf(x,n,p). Without theStatistics Toolbox, as longas n is a non-negative in-teger, this will work: r =0:floor(x); sum(factorial(n)./

    (factorial(r).*factorial(n-r))

    .*p.^r.*(1-p).^(n-r)). (Unfor-tunately, Matlab s nchoosekfunction wont take a vector argu-ment for k.)

    pbinom(x,n,p)

    205 Compute probability that arandom variable from thePoisson() distribution is lessthan or equal to x.

    poisscdf(x,lambda). With-out the Statistics Toolbox, aslong as lambda 0, thiswill work: r = 0:floor(x);sum(exp(-lambda)*lambda.^r

    ./factorial(r))

    ppois(x,lambda)

    206 Compute cumulative distri-bution function at x for arandom variable from the ex-ponential distribution withmean .

    expcdf(x,mu) or(x>=0)*(1-exp(-x/mu)) willwork even without the StatisticsToolbox, as long as mu is positive.

    pexp(x,1/mu)

    207 Compute cumulative distri-bution function at x for a ran-dom variable from the Nor-mal distribution with mean and standard deviation .

    normcdf(x,mu,sigma) or 1/2 -erf(-(x-mu)/(sigma*sqrt(2)))/2

    will work even without the Statis-tics Toolbox, as long as sigma ispositive.

    pnorm(x,mu,sigma)

    208 Compute cumulative distri-bution function at x for a ran-dom variable from the contin-uous uniform distribution oninterval (a, b).

    unifcdf(x,a,b) or(x>a)*(min(x,b)-a)/(b-a) willwork even without the StatisticsToolbox, as long as b > a.

    punif(x,a,b)

    209 Compute probability that arandom variable from the dis-crete uniform distribution onintegers 1 . . . n is less than orequal to x.

    unidcdf(x,n) or(x>=1)*min(floor(x),n)/n willwork even without the StatisticsToolbox, as long as n is a positiveinteger.

    (x>=1)*min(floor(x),n)/n

  • D. Hiebeler, Matlab / R Reference 25

    7 Graphics

    7.1 Various types of plotting

    No. Description Matlab R210 Create a new figure window figure windows() (when running R in Win-

    dows), quartz() (in Mac OS-X), orx11() (in Linux)

    211 Select figure number n figure(n) (will create the figure if itdoesnt exist)

    dev.set(n) (returns the actual de-vice selected; will be different from nif there is no figure device with num-ber n)

    212 List open figure windows get(0,children) (The 0 handlerefers to the root graphics object.)

    dev.list()

    213 Close figure window(s) close to close the current figure win-dow, close(n) to close a specifiedfigure, and close all to close all fig-ures

    dev.off() to close the currently ac-tive figure device, dev.off(n) to closea specified one, and graphics.off()to close all figure devices.

    214 Plot points using open circles plot(x,y,o) plot(x,y)215 Plot points using solid lines plot(x,y) plot(x,y,type=l) (Note: thats a

    lower-case L, not the number 1)216 Plotting: color, point mark-

    ers, linestyleplot(x,y,str) where str is astring specifying color, point marker,and/or linestyle (see table below)(e.g. gs-- for green squares withdashed line)

    plot(x,y,type=str1,

    pch=arg2,col=str3,

    lty=arg4)

    See tables below for possible values ofthe 4 parameters

    217 Plotting with logarithmicaxes

    semilogx, semilogy, and loglogfunctions take arguments like plot,and plot with logarithmic scales forx, y, and both axes, respectively

    plot(..., log=x), plot(...,log=y), and plot(...,log=xy) plot with logarithmicscales for x, y, and both axes,respectively

    218 Make bar graph where the xcoordinates of the bars are inx, and their heights are in y

    bar(x,y) Or just bar(y) if you onlywant to specify heights. Note: if Ais a matrix, bar(A) interprets eachcolumn as a separate set of observa-tions, and each row as a different ob-servation within a set. So a 20 2matrix is plotted as 2 sets of 20 ob-servations, while a 2 20 matrix isplotted as 20 sets of 2 observations.

    Cant do this in R; but barplot(y)makes a bar graph where you specifythe heights, barplot(y,w) also spec-ifies the widths of the bars, and histcan make plots like this too.

    219 Make histogram of values inx

    hist(x) hist(x)

    220 Given vector x containinginteger values, make a bargraph where the x coordi-nates of bars are the values,and heights are the counts ofhow many times the valuesappear in x

    v=unique(x); c=hist(x,v);

    bar(v,c)

    hist(x,(min(x)-.5):(max(x)+.5))

  • D. Hiebeler, Matlab / R Reference 26

    No. Description Matlab R221 Given vector x containing

    continuous values, lump thedata into k bins and make ahistogram / bar graph of thebinned data

    [c,m] = hist(x,k); bar(m,c) orfor slightly different plot style usehist(x,k)

    hist(x,seq(min(x), max(x),

    length.out=k+1))

    222 Make a plot containing error-bars of height s above and be-low (x, y) points

    errorbar(x,y,s) errbar(x,y,y+s,y-s) Note: errbaris part of the Hmisc package (seeitem 295 for how to install/load pack-ages).

    223 Make a plot containing error-bars of height a above and bbelow (x, y) points

    errorbar(x,y,b,a) errbar(x,y,y+a,y-b) Note: errbaris part of the Hmisc package (seeitem 295 for how to install/load pack-ages).

    224 Other types of 2-D plots stem(x,y) and stairs(x,y)for other types of 2-D plots.polar(theta,r) to use polarcoordinates for plotting.

    pie(v)

    225 Make a 3-D plot of some datapoints with given x, y, z co-ordinates in the vectors x, y,and z.

    plot3(x,y,z) This works much likeplot, as far as plotting symbols, line-types, and colors.

    cloud(z~x*y) You can also usearguments pch and col as withplot. To make a 3-D plot withlines, do cloud(z~x*y,type=l,panel.cloud=panel.3dwire)

    226 Surface plot of data in matrixA

    surf(A)

    You can then click on the smallcurved arrow in the figure window(or choose Rotate 3D from theTools menu), and then click anddrag the mouse in the figure to ro-tate it in three dimensions.

    persp(A)

    You can include shading in the im-age via e.g. persp(A,shade=0.5).There are two viewing angles youcan also specify, among other pa-rameters, e.g. persp(A, shade=0.5,theta=50, phi=35).

    227 Surface plot of f(x, y) =sin(x + y)

    y for 100 values

    of x between 0 and 10, and90 values of y between 2 and8

    x = linspace(0,10,100);

    y = linspace(2,8,90);

    [X,Y] = meshgrid(x,y);

    Z = sin(X+Y).*sqrt(Y);

    surf(X,Y,Z)

    shading flat

    x = seq(0,10,100)

    y = seq(2,8,90)

    f = function(x,y)

    return(sin(x+y)*sqrt(y))

    z = outer(x,y,f)

    persp(x,y,z)

    228 Other ways of plotting thedata from the previous com-mand

    mesh(X,Y,Z), surfc(X,Y,Z),surfl(X,Y,Z), contour(X,Y,Z),pcolor(X,Y,Z),waterfall(X,Y,Z). Also see theslice command.

    contour(x,y,z) Or dos=expand.grid(x=x,y=y), andthen wireframe(z~x*y,s) orwireframe(z~x*y,s,shade=TRUE)

    (Note: wireframe is part of thelattice package; see item 295 for howto load packages). If you have vectorsx, y, and z all the same length, youcan also do symbols(x,y,z).

  • D. Hiebeler, Matlab / R Reference 27

    Adding various labels or making adjustments to plotsNo. Description Matlab R229 Set axis ranges in a figure

    windowaxis([x1 x2 y1 y2]) You have to do this when

    you make the plot, e.g.plot(x,y,xlim=c(x1,x2),

    ylim=c(y1,y2))

    230 Add title to plot title(somestring) title(main=somestring)adds a main title,title(sub=somestring) addsa subtitle. You can also includemain= and sub= arguments in aplot command.

    231 Add axis labels to plot xlabel(somestring) andylabel(somestring)

    title(xlab=somestring,

    ylab=anotherstr). You canalso include xlab= and ylab=arguments in a plot command.

    232 Include Greek letters or sym-bols in plot axis labels

    You can use basic TeX com-mands, e.g. plot(x,y);xlabel(\phi^2 + \mu_{i,j})

    or xlabel(fecundity \phi)See also help tex.m and parts ofdoc text props for more aboutbuilding labels using general LaTeXcommands

    plot(x,y,xlab=

    expression(phi^2 + mu[i,j]))

    or plot(x,y,xlab=expression(paste(fecundity , phi)))

    See also help(plotmath) and p.98 of the R Graphics book by PaulMurrell for more.

    233 Change font size to 16 in plotlabels

    For the legends and numerical axislabels, use set(gca, FontSize,16), and for text labels on axesdo e.g. xlabel(my x var,FontSize, 16)

    For on-screen graphics, dopar(ps=16) followed by e.g. a plotcommand. For PostScript or PDFplots, add a pointsize=16 argument,e.g. pdf(myfile.pdf, width=8,height=8, pointsize=16) (seeitems 245 and 246)

    234 Add grid lines to plot grid on (and grid off to turn off) grid() Note that if youll beprinting the plot, the default stylefor grid-lines is to use gray dot-ted lines, which are almost invis-ible on some printers. You maywant to do e.g. grid(lty=dashed,col=black) to use black dashedlines which are easier to see.

    235 Add figure legend to top-leftcorner of plot

    legend(first, second,

    Location, NorthWest)

    legend(topleft,

    legend=c(first, second),

    col=c(red, blue),

    pch=c(*,o))

    Matlab note: sometimes you build a graph piece-by-piece, and then want to manually add a legendwhich doesnt correspond with the order you put things in the plot. You can manually construct a legendby plotting invisible things, then building the legend using them. E.g. to make a legend with black starsand solid lines, and red circles and dashed lines: h1=plot(0,0,k*-); set(h1,Visible, off);h2=plot(0,0,k*-); set(h2,Visible, off); legend([h1 h2], blah, whoa). Just be sureto choose coordinates for your invisible points within the current figures axis ranges.

  • D. Hiebeler, Matlab / R Reference 28

    No. Description Matlab R236 Adding more things to a fig-

    urehold on means everything plottedfrom now on in that figure window isadded to whats already there. holdoff turns it off. clf clears the figureand turns off hold.

    points(...) and lines(...) worklike plot, but add to whats alreadyin the figure rather than clearing thefigure first. points and lines arebasically identical, just with differentdefault plotting styles. Note: axesare not recalculated/redrawn whenadding more things to a figure.

    237 Plot multiple data sets atonce

    plot(x,y) where x and y are 2-Dmatrices. Each column of x is plot-ted against the corresponding col-umn of y. If x has only one column,it will be re-used.

    matplot(x,y) where x and y are 2-Dmatrices. Each column of x is plottedagainst the corresponding column ofy. If x has only one column, it will bere-used.

    238 Plot sin(2x) for x between 7and 18

    fplot(sin(2*x), [7 18]) curve(sin(2*x), 7, 18, 200)

    makes the plot, by sampling thevalue of the function at 200 valuesbetween 7 and 18 (if you dontspecify the number of points, 101is the default). You could do thismanually yourself via commands liketmpx=seq(7,18,200); plot(tmpx,

    sin(2*tmpx)).239 Plot color image of integer

    values in matrix Aimage(A) to use array values asraw indices into colormap, orimagesc(A) to automatically scalevalues first (these both draw row1 of the matrix at the top of theimage); or pcolor(A) (draws row1 of the matrix at the bottom ofthe image). After using pcolor,try the commands shading flat orshading interp.

    image(A) (it rotates the matrix 90 de-grees counterclockwise: it draws row1 of A as the left column of the im-age, and column 1 of A as the bottomrow of the image, so the row numberis the x coord and column number isthe y coord). It also rescales colors. Ifyou are using a colormap with k en-tries, but the value k does not appearin A, use image(A,zlim=c(1,k))to avoid rescaling of colors. Ore.g. image(A,zlim=c(0,k-1)) if youwant values 0 through k1 to be plot-ted using the k colors.

    240 Add colorbar legend to imageplot

    colorbar, after using image orpcolor.

    Use filled.contour(A) ratherthan image(A), although it blursthe data via interpolation, oruse levelplot(A) from the lat-tice package (see item 295 forhow to load packages). To usea colormap with the latter, doe.g. levelplot(A,col.regions=terrain.colors(100)).

    241 Set colormap in image colormap(hot). Instead of hot, youcan also use gray, flag, jet (thedefault), cool, bone, copper, pink,hsv, prism. By default, the lengthof the new colormap is the same asthe currently-installed one; use e.g.colormap(hot(256)) to specify thenumber of entries.

    image(A,col=terrain.colors(100)).The parameter 100 specifies thelength of the colormap. Othercolormaps are heat.colors(),topo.colors(), and cm.colors().

  • D. Hiebeler, Matlab / R Reference 29

    No. Description Matlab R242 Build your own colormap us-

    ing Red/Green/Blue tripletsUse an n 3 matrix; each rowgives R,G,B intensities between 0and 1. Can use as argument withcolormap. E.g. for 2 colors: mycmap= [0.5 0.8 0.2 ; 0.2 0.2 0.7]

    Use a vector of hexadecimal strings,each beginning with # and givingR,G,B intensities between 00 and FF.E.g. c(#80CC33,#3333B3); canuse as argument to col= parameterto image. You can build such avector of strings from vectors of Red,Green, and Blue intensities (eachbetween 0 and 1) as follows (for a2-color example): r=c(0.5,0.2);g=c(0.8,0.2); b=c(0.2,0.7);

    mycolors=rgb(r,g,b).

    Matlab plotting specifications, for use with plot, fplot, semilogx, semilogy, loglog, etc:Symbol Color Symbol Marker Symbol Linestyle

    b blue . point (.) - solid lineg green o circle () : dotted liner red x cross () -. dash-dot linec cyan + plus sign (+) -- dashed linem magenta * asterisk ()y yellow s square ()k black d diamond ()w white v triangle (down) ()

    ^ triangle (up) ()< triangle (left) ()> triangle (right) ()p pentragram starh 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 Descriptionblue Blue a a (similarly for other

    characters, but see .below for an exception

    p points

    green Green 19 solid circle l linesred Red 20 bullet (smaller circle) b bothcyan Cyan 21 open circle c lines part only of b

    magenta Magenta 22 square o lines, points overplottedyellow Yellow 23 diamond h histogram-like linesblack Black 24 triangle point-up s steps#RRGGBB hexadecimal specifica-

    tion of Red, Green,Blue

    25 triangle point-down S another kind of steps

    (Other names) See colors() for list ofavailable color names.

    . rectangle of size 0.01inch, 1 pixel, or 1 point(1/72 inch) dependingon device

    n no plotting

    (See table on next pagefor more)

  • D. Hiebeler, Matlab / R Reference 30

    R plotting specifications for lty (line-type) argument, for use with plot, matplot, points, and lines:lty Description0 blank1 solid2 dashed3 dotted4 dotdash5 longdash6 twodash

    0 1 2 3 4 5

    6 7 8 9 10 11

    12 13 14 15 16 17

    18 19 20 21 22 23

    24 25 AA bb . ##

    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 31

    No. Description Matlab R243 Divide up a figure window

    into smaller sub-figuressubplot(m,n,k) divides the currentfigure window into an m n ar-ray of subplots, and draws in sub-plot number k as numbered in read-ing order, i.e. left-to-right, top-to-bottom. E.g. subplot(2,3,4) se-lects the first sub-figure in the secondrow of a 2 3 array of sub-figures.You can do more complex things,e.g. subplot(5,5,[1 2 6 7]) se-lects the first two subplots in the firstrow, and first two subplots in thesecond row, i.e. gives you a biggersubplot within a 5 5 array of sub-plots. (If you that command followedby e.g. subplot(5,5,3) youll seewhats meant by that.)

    There are several ways to do this, e.g.using layout or split.screen, al-though they arent quite as friendlyas Matlab s. E.g. if you let A = 1 1 21 1 3

    4 5 6

    , then layout(A) will

    divide the figure into 6 sub-figures:you can imagine the figure divide intoa 3 3 matrix of smaller blocks; sub-figure 1 will take up the upper-left22 portion, and sub-figures 26 willtake up smaller portions, according tothe positions of those numbers in thematrix A. Consecutive plotting com-mands will draw into successive sub-figures; there doesnt seem to be a wayto explicitly specify which sub-figureto draw into next.To use split.screen, you cando e.g. split.screen(c(2,1)) tosplit into a 2 1 matrix of sub-figures (numbered 1 and 2). Thensplit.screen(c(1,3),2) splits sub-figure 2 into a 1 3 matrix of smallersub-figures (numbered 3, 4, and 5).screen(4) will then select sub-figurenumber 4, and subsequent plottingcommands will draw into it.A third way to accomplish this isvia the commands par(mfrow=) orpar(mfcol=) to split the figure win-dow, and par(mfg=) to select whichsub-figure to draw into.Note that the above methods are allincompatible with each other.

    244 Force graphics windows toupdate

    drawnow (Matlab normally onlyupdates figure windows when ascript/function finishes and returnscontrol to the Matlab prompt, orunder a couple of other circum-stances. This forces it to updatefigure windows to reflect any recentplotting commands.)

    R automatically updates graphicswindows even before functions/scriptsfinish executing, so its not neces-sary to explictly request it. But notethat some graphics functions (partic-ularly those in the lattice package)dont display their results when calledfrom scripts or functions; e.g. ratherthan levelplot(...) you need to doprint(levelplot(...)). Such func-tions will automatically display theirplots when called interactively fromthe command prompt.

  • D. Hiebeler, Matlab / R Reference 32

    7.2 Printing/saving graphics

    No. Description Matlab R245 To print/save to a PDF file

    named fname.pdfprint -dpdf fname saves the con-tents of currently active figure win-dow

    First do pdf(fname.pdf). Then,do various plotting commandsto make your image, as if youwere plotting in a window. Fi-nally, do dev.off() to close/savethe PDF file. To print the con-tents of the active figure win-dow, do dev.copy(device=pdf,file=fname.pdf); dev.off().(But this will not work if youveturned off the display list viadev.control(displaylist=

    inhibit).)246 To print/save to a PostScript

    file fname.ps or fname.epsprint -dps fname for black &white PostScript; print -dpscfname for color PostScript; print-deps fname for black & whiteEncapsulated PostScript; print-depsc fname for color Encapsu-lated PostScript. The first two saveto fname.ps, while the latter twosave to fname.eps.

    postscript(fname.eps), followedby your plotting commands, fol-lowed by dev.off() to close/savethe file. Note: you may want touse postscript(fname.eps,horizontal=FALSE) to save your fig-ure in portrait mode rather than thedefault landscape mode. To print thecontents of the active figure window,do dev.copy(device=postscript,file=fname.eps); dev.off().(But this will not work if youveturned off the display list viadev.control(displaylist=

    inhibit).) You can also includethe horizontal=FALSE argumentwith dev.copy().

    247 To print/save to a JPEG filefname.jpg with jpeg qual-ity = 90 (higher quality looksbetter but makes the filelarger)

    print -djpeg90 fname jpeg(fname.jpg,quality=90),followed by your plotting commands,followed by dev.off() to close/savethe file.

  • D. Hiebeler, Matlab / R Reference 33

    7.3 Animating cellular automata / lattice simulations

    No. Description Matlab R248 To display images of cellu-

    lar automata or other latticesimulations while running inreal time

    Repeatedly use either pcolor orimage to display the data. Dontforget to call drawnow as well, oth-erwise the figure window will not beupdated with each image.

    If you simply call image repeatedly,there is a great deal of flicker-ing/flashing. To avoid this, afterdrawing the image for the first timeusing e.g. image(A), from thenon only use image(A,add=TRUE),which avoids redrawing the entireimage (and the associated flicker).However, this will soon consume agreat deal of memory, as all drawnimages are saved in the image buffer.There are two solutions to thatproblem: (1) every k time steps,leave off the add=TRUE argumentto flush the image buffer (and getoccasional flickering), where youchoose k to balance the flickeringvs. memory-usage tradeoff; or(2) after drawing the first image,do dev.control(displaylist=inhibit) to prohibit retaining thedata. However, the latter solutionmeans that after the simulation isdone, the figure window will not beredrawn if it is resized, or temporarilyobscured by another window. (Acall to dev.control(displaylist=enable) and then one finalimage(A) at the end of the sim-ulation will re-enable re-drawingafter resizing or obscuring, withoutconsuming extra memory.)

  • D. Hiebeler, Matlab / R Reference 34

    8 Working with files

    No. Description Matlab R249 Create a folder (also known

    as a directory)mkdir dirname dir.create(dirname)

    250 Set/change working directory cd dirname setwd(dirname)251 See list of files in current

    working directorydir dir()

    252 Run commands in file foo.mor foo.R respectively

    foo source(foo.R)

    253 Read data from text filedata.txt into matrix A

    A=load(data.txt) orA=importdata(data.txt) Notethat both routines will ignore com-ments (anything on a line followinga % character)

    A=as.matrix(read.table(

    data.txt)) This will ignorecomments (anything on a linefollowing a # character). To ig-nore comments indicated by %,do A=as.matrix(read.table(data.txt, comment.char=%))

    254 Write data from matrix Ainto text file data.txt

    save data.txt A -ascii write(A, file=data.txt,

    ncolumn=dim(A)[2])

  • D. Hiebeler, Matlab / R Reference 35

    9 Miscellaneous

    9.1 Variables

    No. Description Matlab R255 Assigning to variables x = 5 x

  • D. Hiebeler, Matlab / R Reference 36

    9.2 Strings and Misc.

    No. Description Matlab R269 Line continuation If you want to break up a Matlab

    command over more than one line,end all but the last line with threeperiods: .... E.g.:x = 3 + ...

    4

    In R, you can spread commands outover multiple lines, and nothing extrais necessary. R will continue readinginput until the command is complete.E.g.:x = 3 +

    4

    270 Controlling formatting ofoutput

    format short g andformat long g are handy; seehelp format

    options(digits=6) tells R youd liketo use 6 digits of precision in values itdisplays (it is only a suggestion, notstrictly followed)

    271 Exit the program quit or exit q() or quit()272 Comments % this is a comment # this is a comment273 Print a string disp(hi there) or to

    omit trailing newline usefprintf(hi there)

    print(hi there)

    274 Print a string containing sin-gle quotes

    disp(Its nice) orto omit trailing newlinefprintf(Its nice)

    print(It\s nice) orprint("Its nice")

    275 Give prompt and read input x = input(Enter data:) print(Enter data:)from user x = scan()

    276 Concatenate strings [two hal ves] paste(two hal, ves, sep=)277 Concatenate strings stored in

    a vectorv={two , halves};

    strcat(v{:}) But note thatthis drops trailing spaces onstrings. To avoid that, instead dostrcat([v{:}])

    v=c(two , halves);

    paste(v, collapse=)

    278 Extract substring of a string text1=hi there;text2=text(2:6)

    text1=hi there;

    text2=substr(text1,2,6)

    279 Determine whether elementsof a vector are in a set, andgive positions of correspond-ing elements in the set.

    x = a, aa, bc, c; y

    = da, a, bc, a, bc,

    aa; [tf, loc]=ismember(x,y)

    Then loc contains the locations oflast occurrences of elements of xin the set y, and 0 for unmatchedelements.

    x = c(a, aa, bc, c); y

    = c(da, a, bc, a, bc,

    aa); loc=match(x,y) Then loccontains the locations of first oc-curences of elements of x in the sety, and NA for unmatched elements.

    280 Convert number to string num2str(x) as.character(x)

  • D. Hiebeler, Matlab / R Reference 37

    No. Description Matlab R281 Use sprintf to create a

    formatted string. Use %d forintegers (d stands for dec-imal, i.e. base 10), %f forfloating-point numbers, %efor scientific-notation floatingpoint, %g to automaticallychoose %e or %f based onthe value. You can spec-ify field-widths/precisions,e.g. %5d for integers withpadding to 5 spaces, or %.7ffor floating-point with 7digits of precision. There aremany other options too; seethe docs.

    x=2; y=3.5;

    s=sprintf(x is %d, y=%g, ...

    x, y)

    x=2; y=3.5

    s=sprintf(x is %d, y is %g,

    x, y)

    282 Machine epsilon mach, i.e.difference between 1 and thenext largest double-precisionfloating-point number

    eps (See help eps for various otherthings eps can give.)

    .Machine$double.eps

    283 Pause for x seconds pause(x) Sys.sleep(x)284 Wait for user to press any key pause Dont know of a way to do this in R,

    but scan(quiet=TRUE) will wait untilthe user presses the Enter key

    285 Measure CPU time used todo some commands

    t1=cputime; ...commands... ;

    cputime-t1

    t1=proc.time(); ...commands...

    ; (proc.time()-t1)[1]

    286 Measure elapsed (wall-clock) time used to do somecommands

    tic; ...commands... ; toc ort1=clock; ...commands... ;

    etime(clock,t1)

    t1=proc.time(); ...commands...

    ; (proc.time()-t1)[3]

    287 Print an error message an in-terrupt execution

    error(Problem!) stop(Problem!)

    288 Print a warning message warning(Smaller problem!) warning(Smaller problem!)289 Putting multiple statements

    on one lineSeparate statements by commas orsemicolons. A semicolon at the endof a statement suppresses display ofthe results (also useful even with justa single statement on a line), while acomma does not.

    Separate statements by semicolons.

    290 Evaluate contents of a strings as command(s).

    eval(s) eval(parse(text=s))

    291 Show where a command is which sqrt shows you where the filedefining the sqrt function is (butnote that many basic functions arebuilt in, so the Matlab func-tion file is really just a stub con-taining documentation). This is use-ful if a command is doing somethingstrange, e.g. sqrt isnt working. Ifyouve accidentally defined a variablecalled sqrt, then which sqrt willtell you, so you can clear sqrt toerase it so that you can go back tousing the function sqrt.

    R does not execute commands directlyfrom files, so there is no equivalentcommand.

  • D. Hiebeler, Matlab / R Reference 38

    No. Description Matlab R292 Query/set the search path. path displays the current search path

    (the list of places Matlab searchesfor commands you enter). To add adirectory ~/foo to the beginning ofthe search path, do

    addpath ~/foo -begin

    or to add it to the end of the path,do addpath ~/foo -end (Note: youshould generally add the full pathof a directory, i.e. in Linux or MacOS-X something like ~/foo as aboveor of the form /usr/local/lib/foo,while under Windows it would besomething like C:/foo)

    R does not use a search path to lookfor files.

    293 Startup sequence If a file startup.m exists in thestartup directory for Matlab, itscontents are executed. (See theMatlab docs for how to change thestartup directory.)

    If a file .Rprofile exists in the cur-rent directory or the users home di-rectory (in that order), its contentsare sourced; saved data from the file.RData (if it exists) are then loaded.If a function .First() has been de-fined, it is then called (so the obviousplace to define this function is in your.Rprofile file).

    294 Shutdown sequence Upon typing quit or exit, Matlabwill run the script finish.m if presentsomewhere in the search path.

    Upon typing q() or quit(), R will callthe function .Last() if it has been de-fined (one obvious place to define itwould be in the .Rprofile file)

    295 Install and load a package. Matlab does not have packages. Ithas toolboxes, which you can pur-chase and install. Contributedcode (written by end users) can sim-ply be downloaded and put in a di-rectory which you then add to Mat-labs path (see item 292 for how toadd things to Matlabs path).

    To install e.g. the deSolve pack-age, you can use the commandinstall.packages(deSolve).You then need to load the packagein order to use it, via the commandlibrary(deSolve). When runningR again later youll need to load thepackage again to use it, but youshould not need to re-install it. Notethat the lattice package is typicallyincluded with binary distributions ofR, so it only needs to be loaded, notinstalled.

  • D. Hiebeler, Matlab / R Reference 39

    10 Spatial Modeling

    No. Description Matlab R296 Take an LL matrix A of

    0s and 1s, and seed frac-tion p of the 0s (turn theminto 1s), not changing entrieswhich are already 1.

    A = (A | (rand(L) < p))*1; A = (A | (matrix(runif(L^2),L)

    < p))*1

    297 Take an LL matrix A of 0sand 1s, and kill fraction pof the 1s (turn them into 0s),not changing the rest of theentries

    A = (A & (rand(L) < 1-p))*1; A = (A & (matrix(runif(L^2),L)

    < 1-p))*1

    298 Do wraparound on a coor-dinate newx that youve al-ready calculated. You canreplace newx with x+dx ifyou want to do wraparoundon an offset x coordinate.

    mod(newx-1,L)+1 Note: for porta-bility with other languages such asC which handle MOD of negativevalues differently, you may want toget in the habit of instead doingmod(newx-1+L,L)+1

    ((newx-1) %% L) + 1 Note: forportability with other languages suchas C which handle MOD of nega-tive values differently, you may wantto get in the habit of instead doing((newx-1+L)%%L) + 1

    299 Randomly initialize a portionof an array: set fraction p ofsites in rows iy1 through iy2and columns ix1 through ix2equal to 1 (and set the rest ofthe sites in that block equalto zero). Note: this assumeiy1 < iy2 and ix1 < ix2.

    dx=ix2-ix1+1; dy=iy2-iy1+1;

    A(iy1:iy2,ix1:ix2) = ...

    (rand(dy,dx) < p0)*1;

    dx=ix2-ix1+1; dy=iy2-iy1+1;

    A[iy1:iy2,ix1:ix2] =

    (matrix(runif(dy*dx),dy)