Title: | 'MATLAB' Emulation Package |
---|---|
Description: | Emulate 'MATLAB' code using 'R'. |
Authors: | P. Roebuck |
Maintainer: | P. Roebuck <[email protected]> |
License: | Artistic-2.0 |
Version: | 1.0.4.1 |
Built: | 2024-11-03 06:44:13 UTC |
Source: | CRAN |
Wrapper functions and variables used to replicate MATLAB function calls as best possible to simplify porting.
Package: | matlab |
Type: | Package |
Version: | 1.0.4.1 |
Date: | 2022-05-31 |
License: | Artistic-2.0 |
They are no more complete than absolutely necessary and are quite possibly broken for fringe cases.
For a complete list of functions, use library(help="matlab")
.
For a high-level summary of the changes for each revision, use
file.show(system.file("NEWS", package="matlab"))
.
In certain cases, these may not correspond exactly with MATLAB API as sometimes it just wasn't possible.
P. Roebuck [email protected]
Rounds to the nearest integer.
ceil(x)
ceil(x)
x |
numeric to be rounded |
Simply invokes ceiling
for those more used to C library API name.
Returns numeric vector containing smallest integers not less than the
corresponding elements of argument x
.
P. Roebuck [email protected]
ceil(c(0.9, 1.3, 2.4))
ceil(c(0.9, 1.3, 2.4))
Create cell array.
cell(...)
cell(...)
... |
numeric dimensions for the result |
Returns list consisting of empty matrices. Defaults to square if dimension argument resolves to a single value.
P. Roebuck [email protected]
cell(3) cell(c(3, 3)) # same thing cell(3, 3) # same thing cell(size(matrix(NA, 3, 3))) # same thing
cell(3) cell(c(3, 3)) # same thing cell(3, 3) # same thing cell(size(matrix(NA, 3, 3))) # same thing
Displays colorbar showing the color scale.
colorbar(C, location=c("EastOutside", "WestOutside", "NorthOutside", "SouthOutside"), ...)
colorbar(C, location=c("EastOutside", "WestOutside", "NorthOutside", "SouthOutside"), ...)
C |
numeric vector or matrix representing data values |
location |
character scalar indicating desired orientation with respect to the axes |
... |
graphical parameters for image may also be passed as arguments to this method |
The values of the elements of C
are indices into the current
palette that determine the color of each patch.
This implementation differs a bit from its MATLAB counterpart in that the values must be passed explicitly.
P. Roebuck [email protected]
imagesc
,
jet.colors
,
layout
,
par
doPlot <- function(C, cb.loc=c("EastOutside", "WestOutside", "NorthOutside", "SouthOutside"), ...) { saved.par <- par(no.readonly=TRUE) on.exit(par(saved.par)) layout.EO <- function() { ## divide the device into one row and nine columns ## allocate figure 1 the first eight columns ## allocate figure 2 the last column layout(matrix(c(1, 1, 1, 1, 1, 1, 1, 1, 2), ncol=9)) } layout.WO <- function() { ## divide the device into one row and nine columns ## allocate figure 1 the last eight columns ## allocate figure 2 the first column layout(matrix(c(2, 1, 1, 1, 1, 1, 1, 1, 1), ncol=9)) } layout.NO <- function() { ## divide the device into six rows and one column ## allocate figure 1 the last five rows ## allocate figure 2 the first row layout(matrix(c(2, 1, 1, 1, 1, 1), nrow=6)) } layout.SO <- function() { ## divide the device into six rows and one column ## allocate figure 1 the first five rows ## allocate figure 2 the last row layout(matrix(c(1, 1, 1, 1, 1, 2), nrow=6)) } location <- match.arg(cb.loc) switch(EXPR=location, EastOutside = layout.EO(), WestOutside = layout.WO(), NorthOutside = layout.NO(), SouthOutside = layout.SO()) imagesc(C, ...) colorbar(C, location, ...) } values <- matrix(c(seq(1, 5, by=1), seq(2, 10, by=2), seq(3, 15, by=3)), nrow=3, byrow=TRUE) dev.new(width=8, height=7) doPlot(values, "EastOutside", col=jet.colors(16))
doPlot <- function(C, cb.loc=c("EastOutside", "WestOutside", "NorthOutside", "SouthOutside"), ...) { saved.par <- par(no.readonly=TRUE) on.exit(par(saved.par)) layout.EO <- function() { ## divide the device into one row and nine columns ## allocate figure 1 the first eight columns ## allocate figure 2 the last column layout(matrix(c(1, 1, 1, 1, 1, 1, 1, 1, 2), ncol=9)) } layout.WO <- function() { ## divide the device into one row and nine columns ## allocate figure 1 the last eight columns ## allocate figure 2 the first column layout(matrix(c(2, 1, 1, 1, 1, 1, 1, 1, 1), ncol=9)) } layout.NO <- function() { ## divide the device into six rows and one column ## allocate figure 1 the last five rows ## allocate figure 2 the first row layout(matrix(c(2, 1, 1, 1, 1, 1), nrow=6)) } layout.SO <- function() { ## divide the device into six rows and one column ## allocate figure 1 the first five rows ## allocate figure 2 the last row layout(matrix(c(1, 1, 1, 1, 1, 2), nrow=6)) } location <- match.arg(cb.loc) switch(EXPR=location, EastOutside = layout.EO(), WestOutside = layout.WO(), NorthOutside = layout.NO(), SouthOutside = layout.SO()) imagesc(C, ...) colorbar(C, location, ...) } values <- matrix(c(seq(1, 5, by=1), seq(2, 10, by=2), seq(3, 15, by=3)), nrow=3, byrow=TRUE) dev.new(width=8, height=7) doPlot(values, "EastOutside", col=jet.colors(16))
Create an identity matrix.
eye(m, n)
eye(m, n)
m , n
|
numeric scalar specifying dimensions for the result |
Returns matrix of order 1.
Defaults to square if second dimension argument n
not provided.
P. Roebuck [email protected]
eye(3)
eye(3)
Performs prime factorization.
factors(n)
factors(n)
n |
numeric scalar specifying composite number to be factored |
Computes the prime factors of n
in ascending order, each one as often
as its multiplicity requires, such that n == prod(factors(n))
.
Returns vector containing the prime factors of n
.
The corresponding MATLAB function is called 'factor', but was renamed here to avoid conflict with R's compound object class.
H. Borchers [email protected], P. Roebuck [email protected]
factors(1002001) # 7 7 11 11 13 13 factors(65537) # is prime ## Euler's calculation factors(2^32 + 1) # 641 6700417
factors(1002001) # 7 7 11 11 13 13 factors(65537) # is prime ## Euler's calculation factors(2^32 + 1) # 641 6700417
Return filename parts.
fileparts(pathname)
fileparts(pathname)
pathname |
character string representing pathname to be parsed |
Determines the path, filename, extension, and version for the specified file.
The returned ext
contains a dot (.) before the file extension.
The returned versn
is always an empty string as the field is provided
for compatibility with its namesake's results.
Returns a list with components:
pathstr |
character string representing directory path |
name |
character string representing base of file name |
ext |
character string representing file extension |
versn |
character string representing version. Unused |
Returns same insane results as does its namesake when handling relative
directories, UNIX hidden files, and tilde expansion. Hidden files are
returned with name
containing a zero length vector and ext
containing the actual name.
For best results, use this routine to process files, not directories.
P. Roebuck [email protected]
## Rename dot-txt file as dot-csv ans <- fileparts("/home/luser/foo.txt") fullfile(ans$pathstr, paste(ans$name, "csv", sep=".")) # /home/luser/foo.csv
## Rename dot-txt file as dot-csv ans <- fileparts("/home/luser/foo.txt") fullfile(ans$pathstr, paste(ans$name, "csv", sep=".")) # /home/luser/foo.csv
Returns the character that separates directory names in filenames.
filesep
filesep
Variable that contains the value of .Platform$file.sep
.
Returns character representing this platform's file separator.
Implemented as an R variable rather than a function such that it more closely resembles normal MATLAB usage.
P. Roebuck [email protected]
Finds indices of elements.
find(x)
find(x)
x |
expression to evaluate |
If expression is not logical, finds indices of nonzero elements of
argument x
.
Returns indices of corresponding elements matching the expression x
.
P. Roebuck [email protected]
find(-3:3 >= 0) find(c(0, 1, 0, 2, 3))
find(-3:3 >= 0) find(c(0, 1, 0, 2, 3))
Rounds toward zero.
fix(A)
fix(A)
A |
numeric to be rounded |
Simply invokes trunc
.
Returns vector containing integers by truncating the
corresponding values of argument A
toward zero.
P. Roebuck [email protected]
fix(c(1.3, 2.5, 3.7))
fix(c(1.3, 2.5, 3.7))
Flips matrices either left-right or up-down.
fliplr(object) flipud(object)
fliplr(object) flipud(object)
object |
vector or matrix to be flipped |
These are S4 generic functions.
Return value is the same type as argument object
.
P. Roebuck [email protected]
fliplr(1:9) flipud(1:9) # same as previous since vectors have no orientation in R fliplr(matrix(1:9, 3, 3, byrow=TRUE)) flipud(matrix(1:9, 3, 3, byrow=TRUE))
fliplr(1:9) flipud(1:9) # same as previous since vectors have no orientation in R fliplr(matrix(1:9, 3, 3, byrow=TRUE)) flipud(matrix(1:9, 3, 3, byrow=TRUE))
Contructs path to a file from components in platform-independent manner
fullfile(...)
fullfile(...)
... |
character strings representing path components |
Builds a full filename from the directories and filename specified. This is conceptually equivalent to
paste(dir1, dir2, dir3, filename, sep=filesep)
with care taken to handle cases when directories begin or end with a separator.
Returns character vector of arguments concatenated term-by-term and separated by file separator if all arguments have a positive length; otherwise, an empty character vector.
P. Roebuck [email protected]
fullfile("", "etc", "profile") # /etc/profile
fullfile("", "etc", "profile") # /etc/profile
Create a Hilbert matrix.
hilb(n)
hilb(n)
n |
numeric scalar specifying dimensions for the result |
The Hilbert matrix is a notable example of a poorly conditioned matrix. Its elements are
H[i, j] = 1 / (i + j - 1)
.
Returns an n
-by-n
matrix constructed as described above.
H. Borchers [email protected], P. Roebuck [email protected]
hilb(3)
hilb(3)
Scales image data to the full range of the current palette and displays the image.
imagesc(x=seq(ncol(C)), y=seq(nrow(C)), C, col=jet.colors(12), ...)
imagesc(x=seq(ncol(C)), y=seq(nrow(C)), C, col=jet.colors(12), ...)
x , y
|
locations of grid lines at which the values in |
C |
numeric matrix representing data to be plotted. Note that
|
col |
vector of colors used to display image data |
... |
graphical parameters for image may also be passed as arguments to this method |
Each element of C
corresponds to a rectangular area in the image.
The values of the elements of C
are indices into the current
palette that determine the color of each patch.
The method interprets the matrix data as a table of f(x[i], y[j])
values,
so that the x axis corresponds to column number and the y axis to row number,
with row 1 at the top, i.e., the same as the conventional printed layout
of a matrix.
P. Roebuck [email protected]
values <- matrix(c(seq(1, 5, by=1), seq(2, 10, by=2), seq(3, 15, by=3)), nrow=3, byrow=TRUE) imagesc(values, xlab="cols", ylab="rows", col=jet.colors(16))
values <- matrix(c(seq(1, 5, by=1), seq(2, 10, by=2), seq(3, 15, by=3)), nrow=3, byrow=TRUE) imagesc(values, xlab="cols", ylab="rows", col=jet.colors(16))
Determine if object is empty.
isempty(A)
isempty(A)
A |
object to evaluate |
An empty object has at least one dimension of size zero.
Returns TRUE
if x
is an empty object; otherwise, FALSE
.
P. Roebuck [email protected]
isempty(1:3) # FALSE isempty(array(NA, c(2, 0, 2))) # TRUE
isempty(1:3) # FALSE isempty(array(NA, c(2, 0, 2))) # TRUE
Array elements that are prime numbers.
isprime(x)
isprime(x)
x |
numeric vector or matrix containing nonnegative integer values |
Returns an array (or vector) the same size as x
containing logical
1 (true
) for the elements of x
which are prime, and logical
0 (false
) otherwise.
H. Borchers [email protected], P. Roebuck [email protected]
x <- c(2, 3, 0, 6, 10) ans <- isprime(x) ## 1, 1, 0, 0, 0 as.logical(ans) ## true, true, false, false, false
x <- c(2, 3, 0, 6, 10) ans <- isprime(x) ## 1, 1, 0, 0, 0 as.logical(ans) ## true, true, false, false, false
Creates a vector of n
colors beginning with dark blue, ranging through
shades of blue, cyan, green, yellow and red, and ending with dark red.
jet.colors(n)
jet.colors(n)
n |
numeric scalar specifying number of colors to be in the palette |
Returns vector of n
color names. This can be used either to create
a user-defined color palette for subsequent graphics, a col=
specification in graphics functions, or in par
.
P. Roebuck [email protected]
require(graphics) x <- 1:16 pie(x, col=jet.colors(length(x)))
require(graphics) x <- 1:16 pie(x, col=jet.colors(length(x)))
Generate linearly spaced vectors.
linspace(a, b, n=100)
linspace(a, b, n=100)
a |
numeric scalar specifying starting point |
b |
numeric scalar specifying ending point |
n |
numeric scalar specifying number of points to be generated |
Similar to colon operator but gives direct control over the number of points.
Note also that although MATLAB doesn't specifically document this, the number
of points generated is actually floor(n)
.
Returns vector containing containing n
points linearly spaced
between a
and b
inclusive. If , the
result will be the ending point
b
.
P. Roebuck [email protected]
linspace(1, 10, 4)
linspace(1, 10, 4)
Generate logarithmically spaced vectors.
logspace(a, b, n=50)
logspace(a, b, n=50)
a |
numeric scalar specifying exponent for starting point |
b |
numeric scalar specifying exponent for ending point |
n |
numeric scalar specifying number of points to be generated |
Useful for creating frequency vectors, it is a logarithmic equivalent
of linspace
.
Returns vector containing containing n
points logarithmically
spaced between decades and
. For
,
b
is returned.
P. Roebuck [email protected]
logspace(1, pi, 36)
logspace(1, pi, 36)
Create a magic square.
magic(n)
magic(n)
n |
numeric scalar specifying dimensions for the result |
The value of the characteristic sum for a magic square of order n
is
. The order
n
must be a scalar greater than or
equal to 3; otherwise, the result will be either a nonmagic square, or
else the degenerate magic squares 1 and [].
Returns an n
-by-n
matrix constructed from
the integers 1
through with equal row and column sums.
A magic square, scaled by its magic sum, is doubly stochastic.
P. Roebuck [email protected]
magic(3)
magic(3)
Generate X and Y matrices for three-dimensional plots.
meshgrid(x, y, z, nargout=2)
meshgrid(x, y, z, nargout=2)
x , y , z
|
numeric vectors of values |
nargout |
numeric scalar that determines number of dimensions to return |
In the first example below, the domain specified by vectors x
and y
are transformed into two arrays which can be used to evaluate functions of two
variables and three-dimensional surface plots. The rows of the output array
x
are copies of the vector x
; columns of the output array y
are copies of the vector y
.
The second example below is syntactic sugar for specifying
meshgrid(x, x)
.
The third example below produces three-dimensional arrays used to evaluate functions of three variables and three-dimensional volumetric plots.
Returns list containing eiher two or three matrices depending on the
value of nargout
.
x , y , z
|
output matrices |
Limited to two- or three-dimensional Cartesian space.
P. Roebuck [email protected]
meshgrid(1:3, 10:14) # example 1 meshgrid(1:3) # example 2 meshgrid(5:8, 10:14, 2:3, 3) # example 3
meshgrid(1:3, 10:14) # example 1 meshgrid(1:3) # example 2 meshgrid(5:8, 10:14, 2:3, 3) # example 3
Provides modulus and remainder after division.
mod(x, y) rem(x, y)
mod(x, y) rem(x, y)
x , y
|
numeric vectors or objects |
Returns vector containing result of the element by element operations.
P. Roebuck [email protected]
## same results with x, y having the same sign mod(5, 3) rem(5, 3) ## same results with x, y having different signs mod(-5, 3) rem(-5, 3)
## same results with x, y having the same sign mod(5, 3) rem(5, 3) ## same results with x, y having different signs mod(-5, 3) rem(-5, 3)
Creates a vector of colors equivalent to MATLAB's default colors to use for multiline plots.
multiline.plot.colors()
multiline.plot.colors()
This is equivalent to the MATLAB command
get(gca, 'ColorOrder')
Returns vector of color names. This can be used either to create
a user-defined color palette for subsequent graphics, a col=
specification in graphics functions, or in par
.
Method should be considered experimental and will most likely be removed and replaced with similar functionality in the near future.
P. Roebuck [email protected]
require(graphics) x <- matrix(1:16, nrow=2, byrow=TRUE) matplot(x, type="l", col=multiline.plot.colors())
require(graphics) x <- matrix(1:16, nrow=2, byrow=TRUE) matplot(x, type="l", col=multiline.plot.colors())
Provides number of array dimensions.
ndims(A)
ndims(A)
A |
object of which to determine the number of dimensions |
Simply invokes length(size(A))
.
Returns the number of dimensions in the array A
.
The number of dimensions is always greater than or equal to 2.
Initial implementation returned length
.
P. Roebuck [email protected]
ndims(2:9) # 2 ndims(magic(4)) # 2 ndims(array(1:8, c(2,2,2))) # 3
ndims(2:9) # 2 ndims(magic(4)) # 2 ndims(array(1:8, c(2,2,2))) # 3
Smallest power of 2 greater than or equal to its argument.
nextpow2(x)
nextpow2(x)
x |
numeric or complex value(s). |
Computes the smallest power of two that is greater than or equal to the
absolute value of x
. (That is, p
that satisfies
).
For negative or complex values, the absolute value will be taken.
Returns numeric result containing integer p
as described above.
Nonscalar input returns an element-by-element result (of same size/dimensions
as its input).
H. Borchers [email protected], P. Roebuck [email protected]
nextpow2(10) # 4 nextpow2(1:10) # 0 1 2 2 3 3 3 3 4 4 nextpow2(-2^10) # 10 nextpow2(.Machine$double.eps) # -52 nextpow2(c(0.5, 0.25, 0.125)) # -1 -2 -3
nextpow2(10) # 4 nextpow2(1:10) # 0 1 2 2 3 3 3 3 4 4 nextpow2(-2^10) # 10 nextpow2(.Machine$double.eps) # -52 nextpow2(c(0.5, 0.25, 0.125)) # -1 -2 -3
Provides number of elements in array A
or subscripted array expression.
numel(A, varargin)
numel(A, varargin)
A |
object of which to determine the number of elements |
varargin |
unimplemented |
Returns prod(size(A))
.
P. Roebuck [email protected]
numel(2:9) # 8 numel(magic(4)) # 16
numel(2:9) # 8 numel(magic(4)) # 16
Create a matrix consisting of all ones or zeros.
ones(...) zeros(...)
ones(...) zeros(...)
... |
numeric dimensions for the result |
Returns matrix consisting only of ones (or zeros). Defaults to square if dimension argument resolves to a single value.
P. Roebuck [email protected]
ones(3) ones(c(3, 3)) # same thing ones(3, 3) # same thing ones(size(matrix(NA, 3, 3))) # same thing zeros(3)
ones(3) ones(c(3, 3)) # same thing ones(3, 3) # same thing ones(size(matrix(NA, 3, 3))) # same thing zeros(3)
Pad array.
padarray(A, padsize, padval=0, direction=c("both", "pre", "post"))
padarray(A, padsize, padval=0, direction=c("both", "pre", "post"))
A |
vector, matrix, or array to be padded |
|||||||
padsize |
integer vector specifying both amount of padding and the dimension along which to add it |
|||||||
padval |
scalar value specifying pad value, which defaults to 0.
|
|||||||
direction |
character string specifying direction to apply padding.
|
This is an S4 generic function.
Return value is the same type as argument A
with requested padding.
P. Roebuck [email protected]
padarray(1:4, c(0, 2)) # 0 0 [1 2 3 4] 0 0 padarray(1:4, c(0, 2), -1) # -1 -1 [1 2 3 4] -1 -1 padarray(1:4, c(0, 2), -1, "post") # [1 2 3 4] -1 -1 padarray(1:4, c(0, 3), "symmetric", "pre") # 3 2 1 [1 2 3 4] padarray(letters[1:5], c(0, 3), "replicate") # a a a [a b c d e] e e e padarray(letters[1:5], c(0, 3), "circular", "post") # [a b c d e] a b c
padarray(1:4, c(0, 2)) # 0 0 [1 2 3 4] 0 0 padarray(1:4, c(0, 2), -1) # -1 -1 [1 2 3 4] -1 -1 padarray(1:4, c(0, 2), -1, "post") # [1 2 3 4] -1 -1 padarray(1:4, c(0, 3), "symmetric", "pre") # 3 2 1 [1 2 3 4] padarray(letters[1:5], c(0, 3), "replicate") # a a a [a b c d e] e e e padarray(letters[1:5], c(0, 3), "circular", "post") # [a b c d e] a b c
Generate Pascal matrix.
pascal(n, k=0)
pascal(n, k=0)
n |
numeric scalar specifying order |
k |
numeric scalar specifying desired option. Valid values are 0, 1, or 2 |
Specifying returns symmetric positive definite matrix
with integer entries taken from Pascal's triangle.
Specifying returns the lower triangular Cholesky factor
(up to the signs of the columns) of the Pascal matrix.
Specifying returns a cube root of the identity matrix.
Returns matrix of order n
according to specified option k
.
P. Roebuck [email protected]
pascal(4) pascal(3, 2)
pascal(4) pascal(3, 2)
Returns the character that separates directory names in a list such as the PATH environment variable.
pathsep
pathsep
Variable that contains the value of .Platform$path.sep
.
Returns character representing this platform's path separator.
Implemented as an R variable rather than a function such that it more closely resembles normal MATLAB usage.
P. Roebuck [email protected]
Power with base 2.
pow2(f, e)
pow2(f, e)
f |
numeric vector of factors |
e |
numeric vector of exponents for base 2 |
Computes the expression f * 2^e
for corresponding elements of f
and e
. If e
is missing, it sets e
to f
and f
to 1.
Imaginary parts of complex values are ignored unless e
is missing.
Returns numeric vector constructed as described above.
H. Borchers [email protected], P. Roebuck [email protected]
pow2(c(0, 1, 2, 3)) # 1 2 4 8 pow2(c(0, -1, 2, 3), c(0,1,-2,3)) # 0.0 -2.0 0.5 24.0 pow2(1i) # 0.7692389+0.6389613i # For IEEE arithmetic... pow2(1/2, 1) # 1 pow2(pi/4, 2) # pi pow2(-3/4, 2) # -3 pow2(1/2, -51) # .Machine$double.eps pow2(1/2, -1021) # .Machine$double.xmin
pow2(c(0, 1, 2, 3)) # 1 2 4 8 pow2(c(0, -1, 2, 3), c(0,1,-2,3)) # 0.0 -2.0 0.5 24.0 pow2(1i) # 0.7692389+0.6389613i # For IEEE arithmetic... pow2(1/2, 1) # 1 pow2(pi/4, 2) # pi pow2(-3/4, 2) # -3 pow2(1/2, -51) # .Machine$double.eps pow2(1/2, -1021) # .Machine$double.xmin
Generate a list of prime numbers.
primes(n)
primes(n)
n |
scalar numeric specifying largest prime number desired. |
Generates the list of prime numbers less than or equal to n
using a
variant of the basic "Sieve of Eratosthenes" algorithm. This approach is
reasonably fast, but requires a copious amount of memory when n
is
large. A prime number is one that has no other factors other than 1
and itself.
Returns numeric vector containing prime numbers less than or equal to
argument n
.
H. Borchers [email protected], P. Roebuck [email protected]
primes(1000) length(primes(1e6)) # 78498 prime numbers less than one million ## Not run: length(primes(1e7)) # 664579 prime numbers less than ten million length(primes(1e8)) # 5761455 prime numbers less than one hundred million ## End(Not run)
primes(1000) length(primes(1e6)) # 78498 prime numbers less than one million ## Not run: length(primes(1e7)) # 664579 prime numbers less than ten million length(primes(1e8)) # 5761455 prime numbers less than one hundred million ## End(Not run)
Replicate and tile a matrix.
repmat(A, ...)
repmat(A, ...)
A |
vector or matrix to be tiled. Must be numeric, logical, complex or character. |
... |
numeric dimensions for the result |
Returns matrix with value A
tiled to the number of dimensions specified.
Defaults to square if dimension argument resolves to a single value.
P. Roebuck [email protected]
repmat(1, 3) # same as ones(3) repmat(1, c(3, 3)) # same thing repmat(1, 3, 3) # same thing repmat(1, size(matrix(NA, 3, 3))) # same thing repmat(matrix(1:4, 2, 2), 3)
repmat(1, 3) # same as ones(3) repmat(1, c(3, 3)) # same thing repmat(1, 3, 3) # same thing repmat(1, size(matrix(NA, 3, 3))) # same thing repmat(matrix(1:4, 2, 2), 3)
Reshape matrix or array.
reshape(A, ...)
reshape(A, ...)
A |
matrix or array containing the original data |
... |
numeric dimensions for the result |
In the first example below, an m
-by-n
matrix is created whose
elements are taken column-wise from A
. An error occurs if A
does not have elements.
In the second example below, an n
-dimensional array with the same
elements as A
but reshaped to have the size
m
-by-n
-by-p
. The product of the specified dimensions
must be the same as prod(size(A))
.
In the third example below, an n
-dimensional array with the same
elements as A
but reshaped to siz
, a vector representing the
dimensions of the reshaped array. The quantity prod(siz)
must be
the same as prod(size(A))
.
Returns matrix (or array) of requested dimensions containing the elements
of A
.
P. Roebuck [email protected]
Xmat.2d <- matrix(1:12, nrow=4, ncol=3) reshape(Xmat.2d, 6, 2) # example 1 reshape(Xmat.2d, c(6, 2)) # same thing Xarr.3d <- reshape(Xmat.2d, c(6, 2, 1)) # example 2 reshape(Xmat.2d, size(Xarr.3d)) # example 3
Xmat.2d <- matrix(1:12, nrow=4, ncol=3) reshape(Xmat.2d, 6, 2) # example 1 reshape(Xmat.2d, c(6, 2)) # same thing Xarr.3d <- reshape(Xmat.2d, c(6, 2, 1)) # example 2 reshape(Xmat.2d, size(Xarr.3d)) # example 3
Create the Rosser matrix, a classic symmetric eigenvalue test problem.
rosser()
rosser()
The returned matrix has the following features:
a double eigenvalue
three nearly equal eigenvalues
dominant eigenvalues of opposite sign
a zero eigenvalue
a small, nonzero eigenvalue
Returns an 8
-by-8
matrix with integer elements.
P. Roebuck [email protected]
rosser()
rosser()
Rotates matrix counterclockwise k*90
degrees.
rot90(A, k=1)
rot90(A, k=1)
A |
matrix to be rotated |
k |
numeric scalar specifying the number of times to rotate (1..4) |
Rotating 4 times (360 degrees) returns the original matrix unchanged.
Returns matrix corresponding to argument A
having been rotated
argument k
number of times.
P. Roebuck [email protected]
rot90(matrix(1:4, 2, 2))
rot90(matrix(1:4, 2, 2))
Provides dimensions of X
.
size(X, dimen)
size(X, dimen)
X |
vector, matrix, or array object |
dimen |
numeric scalar specifies particular dimension |
This is an S4 generic function.
Vector will be treated as a single row matrix.
Stored value is equivalent to dim
.
Returns object of class size_t
containing the dimensions of
input argument X
if invoked with a single argument. Returns
integer value of specified dimension if invoked with two arguments.
If dimen
specifies a higher dimension than exists, returns 1
representing the singleton dimension.
Handling of vectors is different than in initial implementation.
Initial implementation returned length
.
P. Roebuck [email protected]
size(2:9) # 1 8 size(matrix(1:8, 2, 4)) # 2 4 size(matrix(1:8, 2, 4), 2) # 4 size(matrix(1:8, 2, 4), 3) # 1
size(2:9) # 1 8 size(matrix(1:8, 2, 4)) # 2 4 size(matrix(1:8, 2, 4), 2) # 4 size(matrix(1:8, 2, 4), 3) # 1
This class represents the dimensions of another R object
Objects can be created by calls of the form new("size_t", ...)
.
Use of generator method is preferred.
.Data
:object of class "integer"
containing size values
Class "integer"
, from data part.
Class "vector"
, by class "integer"
.
Class "numeric"
, by class "integer"
.
Internal class supporting size
.
P. Roebuck [email protected]
Computes the standard deviation of the values of x
.
std(x, flag=0)
std(x, flag=0)
x |
numeric vector or matrix |
flag |
numeric scalar. If |
Simply invokes sd
.
Return value depends on argument x
. If vector, returns the
standard deviation. If matrix, returns vector containing the
standard deviation of each column.
P. Roebuck [email protected]
std(1:2) ^ 2
std(1:2) ^ 2
Compare strings.
strcmp(S, T)
strcmp(S, T)
S , T
|
character vectors to evaluate |
Comparisons are case-sensitive and any leading and trailing blanks in either of the strings are explicitly included in the comparison.
Returns TRUE
if S
is identical to T
;
otherwise, FALSE
.
Value returned is the opposite of the C language convention.
P. Roebuck [email protected]
strcmp("foo", "bar") # FALSE strcmp(c("yes", "no"), c("yes", "no")) # TRUE
strcmp("foo", "bar") # FALSE strcmp(c("yes", "no"), c("yes", "no")) # TRUE
Provides sum of elements.
sum(x, na.rm=FALSE)
sum(x, na.rm=FALSE)
x |
numeric or logical to be summed |
na.rm |
logical scalar. If |
This is an S4 generic function.
Return value depends on argument x
. If vector, returns the same as
sum
. If matrix, returns vector containing the sum of
each column.
P. Roebuck [email protected]
sum(1:9) sum(matrix(1:9, 3, 3))
sum(1:9) sum(matrix(1:9, 3, 3))
Provides stopwatch timer. Function tic
starts the timer and toc
updates the elapsed time since the timer was started.
tic(gcFirst=FALSE) toc(echo=TRUE)
tic(gcFirst=FALSE) toc(echo=TRUE)
gcFirst |
logical scalar. If |
echo |
logical scalar. If |
Provides analog to system.time
.
Function toc
can be invoked multiple times in a row.
P. Roebuck [email protected]
tic() for(i in 1:100) mad(runif(1000)) # kill time toc()
tic() for(i in 1:100) mad(runif(1000)) # kill time toc()
Generate Vandermonde matrix from a vector of numbers.
vander(v)
vander(v)
v |
numeric or complex vector of values |
Generates the Vandermonde matrix whose columns are powers of the vector
v
(of length n
) using the formula
A[i, j] = v[i]^(n-j)
Used when fitting a polynomial to given points.
Returns an n
-by-n
matrix constructed as described above.
H. Borchers [email protected], P. Roebuck [email protected]
vander(1:5)
vander(1:5)