More mathematical epidemiology information to appear...
Home   About us   Mathematical Epidemiology   Rweb   EPITools   Statistics Notes   Web Design   Search   Contact us   Links
> Home > Modeling and Methods > Matlab and R

Matlab and R

This page provides a bit of information on making the transition from Matlab to R (or vice versa), together with a few comparisons with other languages. Each langauge or system has its own strengths and weaknesses; no single system is best for everything. Needless to say, this page makes no effort whatever to include all features of these systems; see the links for further information, details, formal definitions, etc. This page contains only introductory material; think of this as your traveler's phrasebook, rather than as a reference grammar.

Both Matlab and R can be used interactively, or in batch mode. Interactively, the R system prompt is >; the Matlab system prompt on Solaris is >>; and the Scilab system prompt is -->. In what follows, I will sometimes include the system prompt and sometimes not; it will be clear from the context.


Concept Matlab    Scilab    R/S/S-Plus   
Comment % to end of line // to end of line # to end of line
Simple comment % a comment // a comment # a comment


Concept Matlab/Scilab    R/S/S-Plus   
Simple Assignment = <-
Assign the number 7 to the variable a
a =

> a <- 7
> a
[1] 7
Note that following an assignment, the R system is silent; we verified the assignment by typing the variable name a after the system prompt >. When you use Scilab, the prompt is -->. In the future, I will not show the response of the system unless it is specifically needed.

Simple Arithmetic

The usual rules of precedence apply; use parentheses to force addition or subtraction first.
Concept Matlab/Scilab    R/S/S-Plus   
Addition + +
Subtraction - -
Multiplication * *
Division /, \ /
An example
 ans  =
> (8-3)*7+9
[1] 44
In Matlab, a / b means the same as b \ a for scalars; some people pronounce the reverse bar (\) as under, just as the usual division bar / is pronounced over.

Elementary Operations with Strings

Concept Matlab Scilab R
String literal 'i am a string' 'i am a string',
"i am a string"
'i am a string',
"i am a string"
String concatenation strcat() + paste()

Matlab requires a single quote to delimit strings; here is an example using Matlab 5 on Solaris:

>> "aa"
??? "
Use single quote character instead of double quote or backward quote.

>> 'aa'

ans =

Scilab and R both use either a single quote or a double quote to delimit a string.

Here are illustrative examples of string concatenation in Matlab, Scilab, and R. Here, we will prepend a full path to a file name. In Matlab:

>> strcat('/usr/myname/project/','thisfile.m')

ans =


In Scilab:
-->'/usr/myname/project/' + 'thisfile.m'

 ans =


In R:
> paste("/usr/myname/project/", "thisfile.r", sep="")
[1] "/usr/myname/project/thisfile.r"
First, note that R explicitly displays the double quotes when showing a string; Matlab and Scilab do not. Also, observe that the R function paste has the special argument sep. This is because the paste function is more general and can interpose any character as a separator; the default is a blank. To use no character as a separator, we simply enter a blank string, represented by a double quote followed immediately by another double quote.

Finally, Scilab has a strcat() function, but its behavior is somewhat different from the Matlab strcat() function.

Conversion to and from strings

Concept Matlab R
Convert a number to a string representation sprintf(), num2str(), int2str() as.character()
Example of converting to a string a = num2str(3.1) a <- as.character(3.1)
Convert a string to a number str2num(), sscanf() as.numeric()
Example a = str2num('4.4') a <- as.numeric("4.4")

Uniform Random Variables

I use random variables a few times for illustrative examples in this webpage. Much more is available in Matlab, Scilab, R and S.
Concept Matlab/Scilab    R/S/S-Plus   
Standard uniform random variable unifrnd(0,1) runif()
Assign a standard uniform deviate to the variable a
 a <- runif()


Concept Matlab/Scilab    R/S/S-Plus   
Greater than > >
Less than < <
Is equal to == ==
Is not equal to ~= !=
Greater than or equal to >= >=
Less than or equal to <= <=

Boolean Values

Matlab uses nonzero values to represent logical truth and 0 to represent falsehood (similar to the convention used in C). R and S use special values to represent logical truth (similar to the LOGICAL constants of Fortran).
Concept Matlab R S
logical truth 1 or nonzero value TRUE T
logical falsehood 0 FALSE F
Example of assigning boolean values
>> aa = (5>4)
aa =

> aa <- (5>4)
> aa
[1] TRUE
> aa <- (5>4)
> aa
[1] T

Scalar and elementwise boolean operations

Concept Matlab/Scilab    R/S/S-Plus   
And & &
Or | |
Not ~ !
Exclusive Or xor() xor()
Here is an example on how to use the R function xor():
> # R demonstration
> x1 <- 3
> x2 <- 8
> y1 <- 9
> y2 <- 10
> xor(x1>x2, y1<=y2)
[1] TRUE
The R operators & and | are elementwise and and or operators:
> # R demonstration
R also includes two short-circuit logical operators, && and ||. These only use the first element of any vector, and these stop evaluating when the result is determined. For instance:
> # R demonstration
> x <- 0
> # this function will let us know if its argument is evaluated
> #   it simply prints the word evaluated, then its argument, then
> #   a return -- and it returns its argument unchanged.
> sh(x)
evaluated:  0
[1] 0
> sh <- function(x){cat("evaluated: ",x,"\n");x}
> # We attempt to avoid dividing by zero by testing first
> if (x!=0 & 8/sh(x)>0) {print("yes.")}
evaluated:  0
> # note that even though x equaled zero, the second expression
> #  8/sh(x) was evaluated anyway.
> if (x!=0 && 8/sh(x)>0) {print("yes.")}
> # observe that nothing was printed.  Because the system knows
> #   that the conjunction must be false once the first term is
> #   known to be false, the second expression is not even 
> #   evaluated.
The short-circuit forms are important in programming, as illustrated.

Vector boolean operations

Concept Matlab R
Any: true if any element is true any any
All: true if all elements are true all all
Here is an R example:
[1] TRUE
[1] TRUE
> x <- c(0.5,1,2,3)
> any(x<1)
[1] TRUE
> all(x<1)

Interactive Input

Concept Matlab    R/S/S-Plus   
Read interactive input (from a user)
input('a string: ')
Read a number and save it as n
n = input('enter n: ')
#use control-D to terminate

Vectors and Matrices

Concept Matlab/Scilab    R/S/S-Plus   
Create Vector [ ] c()
Create vector of 1, 2, and 3.
-->a=[1 2 3]

> a <- c(1,2,3)
Produce a new vector by adding elements to an existing vector
-->a=[1 2 3]
-->b=[a 4]
> a <- c(1,2,3)
> b <- c(a,4)
Matlab and Scilab distinguish between row and column vectors (both are simply matrices with one column or row, respectively); R, S, and S-Plus support row and column vectors, but also simple vectors. More information will appear below.

Concept Matlab/Scilab    R/S/S-Plus   
Create Row Vector [ ] matrix()
Create row vector of 1, 2, and 3.
-->a=[1 2 3]

> a <- matrix(c(1,2,3),nrow=1)

Concept Matlab/Scilab    R/S/S-Plus   
Create Column Vector [ ] matrix()
Create column vector of 1, 2, and 3.
-->a=[1; 2; 3]
> a <- matrix(c(1,2,3),ncol=1)
In R, use the matrix() function with various options to construct matrices.

Concept Matlab/Scilab    R/S/S-Plus   
Create Matrix [ ] matrix(), rbind(), cbind()
Create a matrix with 1, 2, and 3
in the first row and 4, 5, and 6
in the second row.
-->a=[1 2 3; 4 5 6]
> a <- matrix(c(1,4,2,5,3,6),nrow=2)
> a <- rbind(c(1,2,3),c(4,5,6))
> a <- cbind(c(1,4),c(2,5),c(3,6))
In R, the functions rbind() (row bind) and cbind() (column bind) help construct matrices.

Concept Matlab/Scilab    R/S/S-Plus   
Matrix Multiplication * %*%
Multiply two matrices
-->a=[1 2 3; 4 5 6]
-->b=[4 5;6 7;8 9]
> a <- rbind(c(1,2,3),c(4,5,6))
> b <- rbind(c(4,5),c(6,7),c(8,9))
> a %*% b 
Matlab/Scilab uses * for multiplication of matrices; R/S use %*% for multiplication of matrices.

Concept Matlab/Scilab    R/S/S-Plus   
Elementwise (Hadamard) Matrix Multiplication .* *
Elementwise product of two matrices
-->a=[1 2 3; 4 5 6]
-->b=[4 5 6; 7 8 9]
-->a .* b
> a <- rbind(c(1,2,3),c(4,5,6))
> b <- rbind(c(4,5,6),c(7,8,9))
> a * b 
Matlab/Scilab use the special symbol .* for elementwise multiplication.

Concept Matlab/Scilab    R/S/S-Plus   
Scalar Product * *
Multiply a vector (or matrix) by the constant 2
-->a=[1 2 3; 4 5 6]
-->a * 2
> a <- rbind(c(1,2,3),c(4,5,6))
> a * 2 
Scalar multiplication is straightforward in both languages.

Concept Matlab/Scilab    R/S/S-Plus   
Matrix of zeros zeros() matrix()
Generate a 3 by 4 matrix of zeros
> a <- matrix(0,nrow=3,ncol=4)
Matlab/Scilab provide a special function for creating a matrix of zeros; R/S use the general constructor matrix().

Concept Matlab/Scilab    R/S/S-Plus   
Add a constant to every element of a vector or matrix + +
Demonstrate adding a constant
-->a=[1 2 3; 4 5 6];a+1
> a <- cbind(c(1,4),c(2,5),c(3,6));a+1
Adding a constant to every element of a vector or matrix is simple in both languages.

Concept Matlab/Scilab    R/S/S-Plus   
Combination of vectors into matrices [] rbind(), cbind()
Demonstrate combining vectors into matrices by stacking row vectors
-->a=[1 2 3]
b=[4 5 6]
> a <- c(1,2,3)
b <- c(4,5,6)
d <- rbind(a,b)
Demonstrate combining vectors into matrices by standing column vectors
d=[a b]
> a <- c(1,2,3)
b <- c(4,5,6)
d <- cbind(a,b)
The Matlab/Scilab [] operator is very general and elegant; R/S use the rbind() and cbind() functions to achieve the same effect.

Concept Matlab/Scilab    R/S/S-Plus   
Add a column vector to every column of a matrix duplicate column and add as usual (*) +
Demonstrate adding a column vector to every column
-->a=[1 2 3; 4 5 6]
-->b=[5; 10];
-->a+[b b b]
> a <- cbind(c(1,4),c(2,5),c(3,6))
> b<-c(5,10)
> a+b
Demonstrate adding a row vector to every row
-->a=[1 2 3; 4 5 6]
-->b=[5 10 15]
> a <- cbind(c(1,4),c(2,5),c(3,6))
> b<-c(5,10,15)
> t(t(a)+b)
R's addition operator is slightly more general than this example suggests. In R/S, note that when an expression of the form M+V (with M a matrix and V a vector), the vector V is duplicated over and over until it matches the number of elements of the matrix M, and the addition is performed to M in column order (i.e. down the first column until it is finished, then down the second column, etc.).

Concept Matlab/Scilab    R/S/S-Plus   
Identity Matrix eye() diag()
Create 4 by 4 identity matrix
> a <- diag(4)
R's diag function can also be used to set the diagonals of a matrix.

Concept Matlab/Scilab    R/S/S-Plus   
Transpose a matrix ' t()
Transpose a matrix
-->a=[1 2 3;4 5 6]
> a <- rbind(c(1,2,3),c(4,5,6))
> t(a)

Concept Scilab    R   
Eigenvalues of a square matrix spec() eigen()
Compute eigenvalues of a matrix
-->a=[1 2 3;4 5 6;7 8 9]
> a <- rbind(c(1,2,3),c(4,5,6),c(7,8,9))
> eigen(a)$values
The Scilab function spec() returns a column vectors of the eigenvalues of its argument; R's eigen() function returns a list containing both the eigenvectors and eigenvalues; select the values using the $ operator as shown (more on the $ operator later).

Concept Matlab/Scilab    R/S   
Subscripting () []
Get the 3d element of a vector
-->a=[1 2 3]
> a <- c(1,2,3)
> a[3]
Get the third element of the second row
-->a=[1 2 3;4 5 6;7 8 9]
> a<-rbind(c(1,2,3),c(4,5,6),c(7,8,9))
> a[2,3]
[1] 6
Get the second row of a matrix
-->a=[1 2 3;4 5 6;7 8 9]
> a<-rbind(c(1,2,3),c(4,5,6),c(7,8,9))
> a[2,]
Get the third column of a matrix
-->a=[1 2 3;4 5 6;7 8 9]
> a<-rbind(c(1,2,3),c(4,5,6),c(7,8,9))
> a[,3]
Note the difference between the syntax for selecting a row or column between the two systems.

Concept Scilab    R   
Sequences :, linspace() :, seq()
Vector of elements 1 through 10
> a <- 1:10
Vector of elements 1 through 10, by 0.5
> a <- seq(1,10,by=0.5)
Vector of 12 equally spaced elements, starting at 3 and ending at 17
> a <- seq(3,17,length=12)
The Matlab/Scilab : operator produces a row vector; the R/S : operator produces a vector. The Matlab/Scilab : operator may also take three arguments; the R/S : operator only takes two, since the seq() function may be used instead. The R/S seq() function has other options not shown here.

Concept Matlab/Scilab    R/S   
Subsets of a Matrix () []
Select elements 3 through 5 of a vector
> a <- 10:20
> a[3:5]
Select the second, seventh, and third elements of a vector
> a <- 10:20
> a[c(2,7,3)]
Select the second, seventh, and third columns of a matrix
> a <- rbind(10:20,seq(0,20,by=2))
> a[,c(2,7,3)]
Select the second, seventh, and third rows of a matrix
> a <- cbind(10:20,seq(0,20,by=2))
> a[c(2,7,3),]
Select everything but the second element of a vector
> a <- 10:14
> a[-2]
[1] 10 12 13 14
Note the use of the negative subscript in R/S to denote exclusion.

Concept Scilab    R   
Matrix Inversion inv solve
Invert a square matrix
> a <- rbind(c(1,2),c(3,4))
> solve(a)

Decision (Alternation, If)

Concept Matlab/Scilab    R/S/S-Plus   
Decision if-else-end if-else
value = 5*(1:100)
n = input('enter n: ')
if  n>100|n<1
  'error; n out of range 1-100'
  choice = value(n)
value <- 5*(1:100)
n <- scan()
if ( n>100 | n<1 ) {
  print("error; number out of range 1-100")
} else {
  choice <- value(n)
Observe that in R, the condition is enclosed in parentheses, and that braces are used to collect the statements in the if- and else- sections. (However, they are not necessary if you have a single statement; it is a good idea to use them in this case anyway.)

Counted Loop (Repetition, DO, for)

Concept Matlab/Scilab    R/S/S-Plus   
Counted loop for-end for
for ii = 1:10
  jj = ii*ii
for (ii in 1:10) {
  jj <- ii*ii
Nested loops
aa = zeros(4,4)
for ii = 1:4
  for jj = 1:4
aa <- matrix(0,nrow=4,ncol=4)
for (ii in 1:4) {
  for (jj in 1:4) {
    aa[ii,jj] <- ii*jj
The first example simply prints the squares of the numbers from 1 to 10. Observe the use of the braces in R to group statements following the loop header. The second example illustrates nested loops by creating a multiplication table in the matrix aa.

Here is a slightly more general example of the for loop in R. Here, we will loop through a series of (fictitious) machine names, and append to each of them:

for (machine in c("orion","andromeda","centarus","cassiopeia")) {
Observe that in R, we can have a vector of strings, and that we can loop through the values of this vector the same way we can loop through a vector of integers or in fact a vector of anything else. In Matlab, ['aa','bb'] is interpreted as 'aabb', i.e. a single vector containing four characters rather than as a vector of two strings.

While Loop

Concept Matlab/Scilab    R/S/S-Plus   
While loop while-end while
uu = unifrnd(0,1)
while uu<0.2
  uu = unifrnd(0,1)
uu <- runif()
while (uu<0.2) {
  uu <- runif()
The example keeps generating random numbers until it gets one larger than 0.2.


Concept Matlab/Scilab    R   
Function Definition write a function M-file function()
Define a function to return the
sum and product of its two arguments
function name
formal parameters
formal return values

function [w1,w2] = testfn(aa,bb) w1 = aa + bb w2 = aa * bb
testfn <- function(aa,bb) { 

Consult the "Local Guide" to make sure you are loading the definitions correctly in Matlab; in Matlab 5 on Solaris, it is sufficient to place the M-file in the working directory and Matlab can find the function when it is called, and it is the file name that determines the name that is used to call the function. In Scilab the function getf can be used to explicitly load the function. In R, the definition is simply an assignment statement and can be in some R text file which must be sourced in; interactive definition is also possible. There is no necessary connection between a file name and a function definition in R; many functions can be defined in the same file.

Observe that Matlab supports multiple return value syntax; in R, you must return a composite object containing all the objects you wish to return. In Matlab and Scilab, values are returned by assigning values to the formal return variables, as shown in the example. In R, the last expression evaluated is the value returned by the function; no formal return variables are needed.

Observe that the function definition in R is simply an assignment. In R, functions are first-class objects; they can be not only called, but also passed as arguments and returned as values from other functions. There will be more information on this below.

Concept Matlab    R   
Function call foo(arg1,arg2,...) foo(arg1,arg2,...)
Call a function and
assign the result to a (some) variable(s)
(See previous example.)
-->[var1,var2] = testfn(3,4)
> varlist <- testfn(3,4)
Call an anonymous function  
> (function(a,b){a+b})(4,5)
[1] 9

Notice that the Matlab example simultaneously assigned values to the variables var1 and var2; the R example returned a list containing both the desired values and assigned this to varlist.

The items in the return value object in R can be named for convenience; this is a useful idiom:

> testfn <- function(aa,bb) {
+   list(sum=aa+bb,product=aa*bb)
+ }
> val <- testfn(3,4)
> val$sum
[1] 7
> val$product
[1] 12

Also, note that a function in R need not be named. The expression function(a,b){a+b} represents the function that adds its arguments. It can be used directly in a function call expression as shown in the last line in the table, where it is applied to the two arguments 4 and 5. Anonymous functions are called lambda expressions in Lisp and some other languages.

All content © 2002 Mathepi.Com (except R and Rweb).
About us.