Search This Blog

Friday, May 31, 2013

R for MATLAB users

R for MATLAB users

Help

R/S-PlusMATLAB/OctaveDescription
help.start()doc
help -i % browse with Info
Browse help interactively
help()help help or doc docHelp on using help
help(plot) or ?plothelp plotHelp for a function
help(package='splines')help splines or doc splinesHelp for a toolbox/library package
demo()demoDemonstration examples
example(plot)
Example using a function

Searching available documentation

R/S-PlusMATLAB/OctaveDescription
help.search('plot')lookfor plotSearch help files
apropos('plot')
Find objects by partial name
library()helpList available packages
find(plot)which plotLocate functions
methods(plot)
List available methods for a function

Using interactively

R/S-PlusMATLAB/OctaveDescription
Rguioctave -qStart session
source('foo.R')foo(.m)Run code from file
history()historyCommand history
savehistory(file=".Rhistory")diary on [..] diary offSave command history
q(save='no')exit or quitEnd session

Operators

R/S-PlusMATLAB/OctaveDescription
help(Syntax)help -Help on operator syntax

Arithmetic operators

R/S-PlusMATLAB/OctaveDescription
a<-1 b="" tt="">a=1; b=2;Assignment; defining a number
a + ba + bAddition
a - ba - bSubtraction
a * ba * bMultiplication
a / ba / bDivision
a ^ ba .^ bPower, $a^b$
a %% brem(a,b)Remainder
a %/% b
Integer division
factorial(a)factorial(a)Factorial, $n!$

Relational operators

R/S-PlusMATLAB/OctaveDescription
a == ba == bEqual
a < ba < bLess than
a > ba > bGreater than
a <= ba <= bLess than or equal
a >= ba >= bGreater than or equal
a != ba ~= bNot Equal

Logical operators

R/S-PlusMATLAB/OctaveDescription
a && ba && bShort-circuit logical AND
a || ba || bShort-circuit logical OR
a & ba & b or and(a,b)Element-wise logical AND
a | ba | b or or(a,b)Element-wise logical OR
xor(a, b)xor(a, b)Logical EXCLUSIVE OR
!a~a or not(a)
~a or !a
Logical NOT

any(a)True if any element is nonzero

all(a)True if all elements are nonzero

root and logarithm

R/S-PlusMATLAB/OctaveDescription
sqrt(a)sqrt(a)Square root
log(a)log(a)Logarithm, base $e$ (natural)
log10(a)log10(a)Logarithm, base 10
log2(a)log2(a)Logarithm, base 2 (binary)
exp(a)exp(a)Exponential function

Round off

R/S-PlusMATLAB/OctaveDescription
round(a)round(a)Round
ceil(a)ceil(a)Round up
floor(a)floor(a)Round down

fix(a)Round towards zero

Mathematical constants

R/S-PlusMATLAB/OctaveDescription
pipi$\pi=3.141592$
exp(1)exp(1)$e=2.718281$

Missing values; IEEE-754 floating point status flags

R/S-PlusMATLAB/OctaveDescription

NaNNot a Number

InfInfinity, $\infty$

Complex numbers

R/S-PlusMATLAB/OctaveDescription
1iiImaginary unit
z <- 3="" i="" tt="">z = 3+4iA complex number, $3+4i$
abs(3+4i) or Mod(3+4i)abs(z)Absolute value (modulus)
Re(3+4i)real(z)Real part
Im(3+4i)imag(z)Imaginary part
Arg(3+4i)arg(z)Argument
Conj(3+4i)conj(z)Complex conjugate

Trigonometry

R/S-PlusMATLAB/OctaveDescription
atan2(b,a)atan(a,b)Arctangent, $\arctan(b/a)$

Generate random numbers

R/S-PlusMATLAB/OctaveDescription
runif(10)rand(1,10)Uniform distribution
runif(10, min=2, max=7)2+5*rand(1,10)Uniform: Numbers between 2 and 7
matrix(runif(36),6)rand(6)Uniform: 6,6 array
rnorm(10)randn(1,10)Normal distribution

Vectors

R/S-PlusMATLAB/OctaveDescription
a <- c="" tt="">a=[2 3 4 5];Row vector, $1 \times n$-matrix
adash <- c="" t="" tt="">adash=[2 3 4 5]';Column vector, $m \times 1$-matrix

Sequences

R/S-PlusMATLAB/OctaveDescription
seq(10) or 1:101:101,2,3, ... ,10
seq(0,length=10)0:90.0,1.0,2.0, ... ,9.0
seq(1,10,by=3)1:3:101,4,7,10
seq(10,1) or 10:110:-1:110,9,8, ... ,1
seq(from=10,to=1,by=-3)10:-3:110,7,4,1
seq(1,10,length=7)linspace(1,10,7)Linearly spaced vector of n=7 points
rev(a)reverse(a)Reverse

a(:) = 3Set all values to same scalar value

Concatenation (vectors)

R/S-PlusMATLAB/OctaveDescription
c(a,a)[a a]Concatenate two vectors
c(1:4,a)[1:4 a]

Repeating

R/S-PlusMATLAB/OctaveDescription
rep(a,times=2)[a a]1 2 3, 1 2 3
rep(a,each=3)
1 1 1, 2 2 2, 3 3 3
rep(a,a)
1, 2 2, 3 3 3

Miss those elements out

R/S-PlusMATLAB/OctaveDescription
a[-1]a(2:end)miss the first element
a[-10]a([1:9])miss the tenth element
a[-seq(1,50,3)]
miss 1,4,7, ...

a(end)last element

a(end-1:end)last two elements

Maximum and minimum

R/S-PlusMATLAB/OctaveDescription
pmax(a,b)max(a,b)pairwise max
max(a,b)max([a b])max of all values in two vectors
v <- a="" i="" max="" tt="" which.max="">[v,i] = max(a)

Vector multiplication

R/S-PlusMATLAB/OctaveDescription
a*aa.*aMultiply two vectors

dot(u,v)Vector dot product, $u \cdot v$

Matrices

R/S-PlusMATLAB/OctaveDescription
rbind(c(2,3),c(4,5))
array(c(2,3,4,5), dim=c(2,2))
a = [2 3;4 5]Define a matrix

Concatenation (matrices); rbind and cbind

R/S-PlusMATLAB/OctaveDescription
rbind(a,b)[a ; b]Bind rows
cbind(a,b)[a , b]Bind columns

[a(:), b(:)]Concatenate matrices into one vector
rbind(1:4,1:4)[1:4 ; 1:4]Bind rows (from vectors)
cbind(1:4,1:4)[1:4 ; 1:4]'Bind columns (from vectors)

Array creation

R/S-PlusMATLAB/OctaveDescription
matrix(0,3,5) or array(0,c(3,5))zeros(3,5)0 filled array
matrix(1,3,5) or array(1,c(3,5))ones(3,5)1 filled array
matrix(9,3,5) or array(9,c(3,5))ones(3,5)*9Any number filled array
diag(1,3)eye(3)Identity matrix
diag(c(4,5,6))diag([4 5 6])Diagonal

magic(3)Magic squares; Lo Shu

Reshape and flatten matrices

R/S-PlusMATLAB/OctaveDescription
matrix(1:6,nrow=3,byrow=T)reshape(1:6,3,2)';Reshaping (rows first)
matrix(1:6,nrow=2)
array(1:6,c(2,3))
reshape(1:6,2,3);Reshaping (columns first)
as.vector(t(a))a'(:)Flatten to vector (by rows, like comics)
as.vector(a)a(:)Flatten to vector (by columns)
a[row(a) <= col(a)]vech(a)Flatten upper triangle (by columns)

Shared data (slicing)

R/S-PlusMATLAB/OctaveDescription
b = ab = aCopy of a

Indexing and accessing elements (Python: slicing)

R/S-PlusMATLAB/OctaveDescription
a <- 12="" 13="" 14="" c="" rbind="" tt="">
c(21, 22, 23, 24),
c(31, 32, 33, 34))
a = [ 11 12 13 14 ...
21 22 23 24 ...
31 32 33 34 ]
Input is a 3,4 array
a[2,3]a(2,3)Element 2,3 (row,col)
a[1,]a(1,:)First row
a[,1]a(:,1)First column

a([1 3],[1 4]);Array as indices
a[-1,]a(2:end,:)All, except first row

a(end-1:end,:)Last two rows

a(1:2:end,:)Strides: Every other row
a[-2,-3]
All, except row,column (2,3)
a[,-2]a(:,[1 3 4])Remove one column

Assignment

R/S-PlusMATLAB/OctaveDescription
a[,1] <- 99="" tt="">a(:,1) = 99
a[,1] <- c="" tt="">a(:,1) = [99 98 97]'
a[a>90] <- 90="" tt="">a(a>90) = 90;Clipping: Replace all elements over 90

Transpose and inverse

R/S-PlusMATLAB/OctaveDescription
t(a)a'Transpose

a.' or transpose(a)Non-conjugate transpose
det(a)det(a)Determinant
solve(a)inv(a)Inverse
ginv(a)pinv(a)Pseudo-inverse

norm(a)Norms
eigen(a)$valueseig(a)Eigenvalues
svd(a)$dsvd(a)Singular values

chol(a)Cholesky factorization
eigen(a)$vectors[v,l] = eig(a)Eigenvectors
rank(a)rank(a)Rank

Sum

R/S-PlusMATLAB/OctaveDescription
apply(a,2,sum)sum(a)Sum of each column
apply(a,1,sum)sum(a')Sum of each row
sum(a)sum(sum(a))Sum of all elements
apply(a,2,cumsum)cumsum(a)Cumulative sum (columns)

Sorting

R/S-PlusMATLAB/OctaveDescription

a = [ 4 3 2 ; 2 8 6 ; 1 4 7 ]Example data
t(sort(a))sort(a(:))Flat and sorted
apply(a,2,sort)sort(a)Sort each column
t(apply(a,1,sort))sort(a')'Sort each row

sortrows(a,1)Sort rows (by first row)
order(a)
Sort, return indices

Maximum and minimum

R/S-PlusMATLAB/OctaveDescription
apply(a,2,max)max(a)max in each column
apply(a,1,max)max(a')max in each row
max(a)max(max(a))max in array
i <- a="" apply="" tt="" which.max="">[v i] = max(a)return indices, i
pmax(b,c)max(b,c)pairwise max
apply(a,2,cummax)cummax(a)

Matrix manipulation

R/S-PlusMATLAB/OctaveDescription
a[,4:1]fliplr(a)Flip left-right
a[3:1,]flipud(a)Flip up-down

rot90(a)Rotate 90 degrees
kronecker(matrix(1,2,3),a)repmat(a,2,3)
kron(ones(2,3),a)
Repeat matrix: [ a a a ; a a a ]
a[lower.tri(a)] <- 0="" tt="">triu(a)Triangular, upper
a[upper.tri(a)] <- 0="" tt="">tril(a)Triangular, lower

Equivalents to "size"

R/S-PlusMATLAB/OctaveDescription
dim(a)size(a)Matrix dimensions
ncol(a)size(a,2) or length(a)Number of columns
prod(dim(a))length(a(:))Number of elements

ndims(a)Number of dimensions
object.size(a)
Number of bytes used in memory

Matrix- and elementwise- multiplication

R/S-PlusMATLAB/OctaveDescription
a * ba .* bElementwise operations
a %*% ba * bMatrix product (dot product)
outer(a,b) or a %o% b
Outer product
crossprod(a,b) or t(a) %*% b
Cross product
kronecker(a,b)kron(a,b)Kronecker product

a / bMatrix division, $b{\cdot}a^{-1}$
solve(a,b)a \ bLeft matrix division, $b^{-1}{\cdot}a$ \newline (solve linear equations)

Find; conditional indexing

R/S-PlusMATLAB/OctaveDescription
which(a != 0)find(a)Non-zero elements, indices
which(a != 0, arr.ind=T)[i j] = find(a)Non-zero elements, array indices
ij <- 0="" a="" arr.ind="T);" ij="" tt="" v="" which="">[i j v] = find(a)Vector of non-zero values
which(a>5.5)find(a>5.5)Condition, indices
ij <- a="" which="">5.5, arr.ind=T); v <- a="" ij="" tt="">
Return values

a .* (a>5.5)Zero out elements above 5.5

Multi-way arrays

R/S-PlusMATLAB/OctaveDescription

a = cat(3, [1 2; 1 2],[3 4; 3 4]);Define a 3-way array

a(1,:,:)

File input and output

R/S-PlusMATLAB/OctaveDescription
f <- data.txt="" read.table="" tt="">f = load('data.txt')Reading from a file (2d)
f <- data.txt="" read.table="" tt="">f = load('data.txt')Reading from a file (2d)
f <- file="data.csv" read.table="" sep=";" tt="">x = dlmread('data.csv', ';')Reading fram a CSV file (2d)
write(f,file="data.txt")save -ascii data.txt fWriting to a file (2d)

Plotting

Basic x-y plots

R/S-PlusMATLAB/OctaveDescription
plot(a, type="l")plot(a)1d line plot
plot(x[,1],x[,2])plot(x(:,1),x(:,2),'o')2d scatter plot

plot(x1,y1, x2,y2)Two graphs in one plot
plot(x1,y1)
matplot(x2,y2,add=T)
plot(x1,y1)
hold on
plot(x2,y2)
Overplotting: Add new plots to current

subplot(211)subplots
plot(x,y,type="b",col="red")plot(x,y,'ro-')Plotting symbols and color

Axes and titles

R/S-PlusMATLAB/OctaveDescription
grid()grid onTurn on grid lines
plot(c(1:10,10:1), asp=1)axis equal
axis('equal')
replot
1:1 aspect ratio
plot(x,y, xlim=c(0,10), ylim=c(0,5))axis([ 0 10 0 5 ])Set axes manually
plot(1:10, main="title",
xlab="x-axis", ylab="y-axis")
title('title')
xlabel('x-axis')
ylabel('y-axis')
Axis labels and titles

Log plots

R/S-PlusMATLAB/OctaveDescription
plot(x,y, log="y")semilogy(a)logarithmic y-axis
plot(x,y, log="x")semilogx(a)logarithmic x-axis
plot(x,y, log="xy")loglog(a)logarithmic x and y axes

Filled plots and bar plots

R/S-PlusMATLAB/OctaveDescription
plot(t,s, type="n", xlab="", ylab="")
polygon(t,s, col="lightblue")
polygon(t,c, col="lightgreen")
fill(t,s,'b', t,c,'g')
% fill has a bug?
Filled plot
stem(x[,3])
Stem-and-Leaf plot

Functions

R/S-PlusMATLAB/OctaveDescription
f <- -="" cos="" function="" sin="" tt="" x="">f = inline('sin(x/3) - cos(x/5)')Defining functions
plot(f, xlim=c(0,40), type='p')ezplot(f,[0,40])
fplot('sin(x/3) - cos(x/5)',[0,40])
% no ezplot
Plot a function for given range

Polar plots

R/S-PlusMATLAB/OctaveDescription

theta = 0:.001:2*pi;
r = sin(2*theta);


polar(theta, rho)

Histogram plots

R/S-PlusMATLAB/OctaveDescription
hist(rnorm(1000))hist(randn(1000,1))
hist(rnorm(1000), breaks= -4:4)hist(randn(1000,1), -4:4)
hist(rnorm(1000), breaks=c(seq(-5,0,0.25), seq(0.5,5,0.5)), freq=F)

plot(apply(a,1,sort),type="l")plot(sort(a))

3d data

Contour and image plots

R/S-PlusMATLAB/OctaveDescription
contour(z)contour(z)Contour plot
filled.contour(x,y,z,
nlevels=7, color=gray.colors)
contourf(z); colormap(gray)Filled contour plot
image(z, col=gray.colors(256))image(z)
colormap(gray)
Plot image data

quiver()Direction field vectors

Perspective plots of surfaces over the x-y plane

R/S-PlusMATLAB/OctaveDescription
f <- exp="" function="" tt="" x="" y="">
n <- length="40)</tt" seq="">
z <- f="" n="" outer="" tt="">
n=-2:.1:2;
[x,y] = meshgrid(n,n);
z=x.*exp(-x.^2-y.^2);

persp(x,y,z,
theta=30, phi=30, expand=0.6,
ticktype='detailed')
mesh(z)Mesh plot
persp(x,y,z,
theta=30, phi=30, expand=0.6,
col='lightblue', shade=0.75, ltheta=120,
ticktype='detailed')
surf(x,y,z) or surfl(x,y,z)
% no surfl()
Surface plot

Scatter (cloud) plots

R/S-PlusMATLAB/OctaveDescription
cloud(z~x*y)plot3(x,y,z,'k+')3d scatter plot

Save plot to a graphics file

R/S-PlusMATLAB/OctaveDescription
postscript(file="foo.eps")
plot(1:10)
dev.off()
plot(1:10)
print -depsc2 foo.eps
gset output "foo.eps"
gset terminal postscript eps
plot(1:10)
PostScript
pdf(file='foo.pdf')
PDF
devSVG(file='foo.svg')
SVG (vector graphics for www)
png(filename = "Rplot%03d.png"print -dpng foo.pngPNG (raster graphics)

Data analysis

Set membership operators

R/S-PlusMATLAB/OctaveDescription
a <- c="" tt="">
b <- c="" tt="">
a = [ 1 2 2 5 2 ];
b = [ 2 3 4 ];
Create sets
unique(a)unique(a)Set unique
union(a,b)union(a,b)Set union
intersect(a,b)intersect(a,b)Set intersection
setdiff(a,b)setdiff(a,b)Set difference
setdiff(union(a,b),intersect(a,b))setxor(a,b)Set exclusion
is.element(2,a) or 2 %in% aismember(2,a)True for set member

Statistics

R/S-PlusMATLAB/OctaveDescription
apply(a,2,mean)mean(a)Average
apply(a,2,median)median(a)Median
apply(a,2,sd)std(a)Standard deviation
apply(a,2,var)var(a)Variance
cor(x,y)corr(x,y)Correlation coefficient
cov(x,y)cov(x,y)Covariance

Interpolation and regression

R/S-PlusMATLAB/OctaveDescription
z <- lm="" tt="" x="" y="">
plot(x,y)
abline(z)
z = polyval(polyfit(x,y,1),x)
plot(x,y,'o', x,z ,'-')
Straight line fit
solve(a,b)a = x\yLinear least squares $y = ax + b$

polyfit(x,y,3)Polynomial fit

Non-linear methods

Polynomials, root finding

R/S-PlusMATLAB/OctaveDescription
polyroot(c(1,-1,-1))roots([1 -1 -1])Find zeros of polynomial

f = inline('1/x - (x-1)')
fzero(f,1)
Find a zero near $x = 1$

solve('1/x = x-1')Solve symbolic equations

polyval([1 2 1 2],1:10)Evaluate polynomial

Differential equations

R/S-PlusMATLAB/OctaveDescription

diff(a)Discrete difference function and approximate derivative


Solve differential equations

Fourier analysis

R/S-PlusMATLAB/OctaveDescription
fft(a)fft(a)Fast fourier transform
fft(a, inverse=TRUE)ifft(a)Inverse fourier transform

Symbolic algebra; calculus

R/S-PlusMATLAB/OctaveDescription

factor()Factorization

Programming

R/S-PlusMATLAB/OctaveDescription
.R.mScript file extension
#%
% or #
Comment symbol (rest of line)
library(RSvgDevice)% must be in MATLABPATH
% must be in LOADPATH
Import library functions
string <- 234="" a="" tt="">
eval(parse(text=string))
string='a=234';
eval(string)
Eval

Loops

R/S-PlusMATLAB/OctaveDescription
for(i in 1:5) print(i)for i=1:5; disp(i); endfor-statement
for(i in 1:5) {
print(i)
print(i*2)
}
for i=1:5
disp(i)
disp(i*2)
end
Multiline for statements

Conditionals

R/S-PlusMATLAB/OctaveDescription
if (1>0) a <- 100="" tt="">if 1>0 a=100; endif-statement

if 1>0 a=100; else a=0; endif-else-statement
ifelse(a>0,a,0)
Ternary operator (if?true:false)

Debugging

R/S-PlusMATLAB/OctaveDescription
.Last.valueansMost recent evaluated expression
objects()whos or whoList variables loaded into memory
rm(x)clear x or clear [all]Clear variable $x$ from memory
print(a)disp(a)Print

Working directory and OS

R/S-PlusMATLAB/OctaveDescription
list.files() or dir()dir or lsList files in directory
list.files(pattern="\.r$")whatList script files in directory
getwd()pwdDisplays the current working directory
setwd('foo')cd fooChange working directory
system("notepad")!notepad
system("notepad")
Invoke a System Command

No comments:

Post a Comment

Thank you