# Matlab style matrix creation in R, kinda...

Posted on Dec 6, 2011 by Chung-hong Chan

Vector creation using “c(1,2,3,4)”. Vectors in R are similar to lists in Python, it would be more natural to add a little syntactic sugar and use “[1,2,3,4]” for vector creation i.e. the same syntax as Python and many other languages.

[code]
# < -
mdat <- matrix(c(1,2,3, 11,12,13), nrow = 2, ncol=3, byrow=TRUE,
dimnames = list(c("row1", "row2"),
c("C.1", "C.2", "C.3")))
[/code]

[code]
mm <- function(mj) {
mj.sp <- unlist(strsplit(mj, ";"))
for (i in 1:length(mj.sp)) {
mj.row <- unlist(strsplit(mj.sp[i], " "))
mj.row <- as.numeric(mj.row[mj.row!=""])
mj.rowvec <- matrix(mj.row, byrow=TRUE, nrow=1)
if (i == 1){
output.mat <- mj.rowvec
}
else {
output.mat <- rbind(output.mat, mj.rowvec)
}
}
return(output.mat)
}
[/code]

[code]
somematrix <- mm("1 2 3; 2 3 4; 3 4 5; 4 5 6") #4x3 matrix
col.vector <- mm("1; 2; 3; 4; 5") # column vector / 5x1 matrix
row.vector <- mm("1 2 3 4 5") # row vector / 1x5 matrix
[/code]