Home About us Mathematical Epidemiology Rweb EPITools Statistics Notes Web Design Search Contact us Links |
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 | = | <- |
Example Assign the number 7 to the variable a |
-->a=7 |
> a <- 7 |
Concept | Matlab/Scilab | R/S/S-Plus |
Addition | + | + |
Subtraction | - | - |
Multiplication | * | * |
Division | /, \ | / |
An example | -->(8-3)*7+9 ans = 44. | > (8-3)*7+9 [1] 44 |
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 = aaScilab 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 = /usr/myname/project/thisfile.m
-->'/usr/myname/project/' + 'thisfile.m' ans = /usr/myname/project/thisfile.m
> 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.
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") |
Concept | Matlab/Scilab | R/S/S-Plus |
Standard uniform random variable | unifrnd(0,1) | runif() |
Example Assign a standard uniform deviate to the variable a |
a=unifrnd(0,1) |
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 | <= | <= |
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 = 1 |
> aa <- (5>4) > aa [1] TRUE |
> aa <- (5>4) > aa [1] T |
Concept | Matlab/Scilab | R/S/S-Plus |
And | & | & |
Or | | | | |
Not | ~ | ! |
Exclusive Or | xor() | xor() |
> # R demonstration > x1 <- 3 > x2 <- 8 > y1 <- 9 > y2 <- 10 > xor(x1>x2, y1<=y2) [1] TRUEThe R operators & and | are elementwise and and or operators:
> # R demonstration > c(TRUE,TRUE,FALSE,FALSE) & c(TRUE,FALSE,TRUE,FALSE) > [1] TRUE FALSE FALSE FALSE > c(TRUE,TRUE,FALSE,FALSE) & c(TRUE,FALSE,TRUE,FALSE) > [1] TRUE TRUE TRUE FALSER 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.
Concept | Matlab | R |
Any: true if any element is true | any | any |
All: true if all elements are true | all | all |
> any(c(TRUE,TRUE,FALSE)) [1] TRUE > any(c(FALSE,FALSE,FALSE,FALSE)) [1] FALSE > all(c(TRUE,TRUE,FALSE)) [1] FALSE > any(c(TRUE,TRUE,TRUE,TRUE)) [1] TRUE > x <- c(0.5,1,2,3) > any(x<1) [1] TRUE > all(x<1) [1] FALSE
Concept | Matlab | R/S/S-Plus |
Read interactive input (from a user) | input('a string: ') |
scan() |
Read a number and save it as n | n = input('enter n: ') |
n<-scan() |
Concept | Matlab/Scilab | R/S/S-Plus |
Create Vector | [ ] | c() |
Create vector of 1, 2, and 3. | -->a=[1 2 3] or -->a=[1,2,3] |
> a <- c(1,2,3) |
Produce a new vector by adding elements to an existing vector | -->a=[1 2 3] | > a <- c(1,2,3) |
Concept | Matlab/Scilab | R/S/S-Plus |
Create Row Vector | [ ] | matrix() |
Create row vector of 1, 2, and 3. | -->a=[1 2 3] or -->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) |
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)or > a <- rbind(c(1,2,3),c(4,5,6))or > a <- cbind(c(1,4),c(2,5),c(3,6)) |
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*b |
> a <- rbind(c(1,2,3),c(4,5,6)) > b <- rbind(c(4,5),c(6,7),c(8,9)) > a %*% b |
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 |
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 |
Concept | Matlab/Scilab | R/S/S-Plus |
Matrix of zeros | zeros() | matrix() |
Generate a 3 by 4 matrix of zeros | -->zeros(3,4) |
> a <- matrix(0,nrow=3,ncol=4) |
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 |
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] |
> a <- c(1,2,3) |
Demonstrate combining vectors into matrices by standing column vectors | -->a=[1;2;3] |
> a <- c(1,2,3) |
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] |
> a <- cbind(c(1,4),c(2,5),c(3,6)) |
Demonstrate adding a row vector to every row | -->a=[1 2 3; 4 5 6] |
> a <- cbind(c(1,4),c(2,5),c(3,6)) |
Concept | Matlab/Scilab | R/S/S-Plus |
Identity Matrix | eye() | diag() |
Create 4 by 4 identity matrix | -->a=eye(4,4) |
> a <- diag(4) |
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)) |
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)) |
Concept | Matlab/Scilab | R/S |
Subscripting | () | [] |
Get the 3d element of a vector | -->a=[1 2 3] |
> a <- c(1,2,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)) |
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)) |
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)) |
Concept | Scilab | R |
Sequences | :, linspace() | :, seq() |
Vector of elements 1 through 10 | -->a=1:10 |
> a <- 1:10 |
Vector of elements 1 through 10, by 0.5 | -->a=1:0.5:10 |
> a <- seq(1,10,by=0.5) |
Vector of 12 equally spaced elements, starting at 3 and ending at 17 | -->a=linspace(3,17,12) |
> a <- seq(3,17,length=12) |
Concept | Matlab/Scilab | R/S |
Subsets of a Matrix | () | [] |
Select elements 3 through 5 of a vector | -->a=10:20 |
> a <- 10:20 |
Select the second, seventh, and third elements of a vector | -->a=10:20 |
> a <- 10:20 |
Select the second, seventh, and third columns of a matrix | -->a=[10:20;0:2:20] |
> a <- rbind(10:20,seq(0,20,by=2)) |
Select the second, seventh, and third rows of a matrix | -->a=[10:20;0:2:20]' |
> a <- cbind(10:20,seq(0,20,by=2)) |
Select everything but the second element of a vector | -->a=10:14 |
> a <- 10:14 |
Concept | Scilab | R |
Matrix Inversion | inv | solve |
Invert a square matrix | -->a=[1,2;3,4] |
> a <- rbind(c(1,2),c(3,4)) |
Concept | Matlab/Scilab | R/S/S-Plus |
Decision | if-else-end | if-else |
Example | value = 5*(1:100) n = input('enter n: ') if n>100|n<1 'error; n out of range 1-100' else choice = value(n) end |
value <- 5*(1:100) n <- scan() if ( n>100 | n<1 ) { print("error; number out of range 1-100") } else { choice <- value(n) } |
Concept | Matlab/Scilab | R/S/S-Plus |
Counted loop | for-end | for |
Example | for ii = 1:10 jj = ii*ii disp(jj) end |
for (ii in 1:10) { jj <- ii*ii print(jj) } |
Nested loops |
aa = zeros(4,4) for ii = 1:4 for jj = 1:4 aa(ii,jj)=ii*jj end end |
aa <- matrix(0,nrow=4,ncol=4) for (ii in 1:4) { for (jj in 1:4) { aa[ii,jj] <- ii*jj } } |
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 berkeley.edu to each of them:
for (machine in c("orion","andromeda","centarus","cassiopeia")) { print(paste(machine,".berkeley.edu",sep="")) }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.
Concept | Matlab/Scilab | R/S/S-Plus |
While loop | while-end | while |
Example | uu = unifrnd(0,1) while uu<0.2 uu = unifrnd(0,1) end |
uu <- runif() while (uu<0.2) { uu <- runif() } |
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
|
|
testfn <- function(aa,bb) { list(aa+bb,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.