Saturday, November 21, 2015

Matrix in R programming

Posted by   on

Links to all courses
#The hash symbols denote comments. They aren't the part of the commands.
#To create the following matrix
# 1  4  7
# 4  7  8
# 6  6  9
matrix(c(1,4,6,4,7,6,7,8,9),3,3)
#By default the values are taken column wise.
#3,3 represents the number of rows and columns
#respectively.
#However only either row or column may be specified.
#In that case, the other will be automatically adjusted.
#so, alternative
matrix(c(1,4,6,4,7,6,7,8,9),3)
#or. If we leave row unspecified, then there needs a comma
#before column number
matrix(c(1,4,6,4,7,6,7,8,9),,3)
#If we want to arrange values row wise
matrix(1:9,,3,byrow=T)
#or in short
matrix(1:9,,3,T)
#By default, it would be
matrix(1:9,3)
#generating 700000 observations from uniform distribution
#in 7 columns
matrix(runif(700000),,7)
#examples: execute to visualize!
matrix(c(1:19,23),,4)
#if there inadequate values, then values would be recycled
#but with a warning.
matrix(c(17,19,20,22,25),3)
#Let's call our initial matrix y and add 1 to all
elements.
y+1
#see [2,3]th element of y where 2 is for row and 3 for
#column
y[2,3]
#all columns of 1st row
y[1,]
#all rows of 2nd column
y[,2]
#Replacing elements e.g, to make all column values of 2nd
#row 10.
y[2,]=10
#Replace 1st three elements of 3rd column by 1, 3 & 4
respectively
y[1:3,3]=c(1,3,4)
#make a matrix having elements 1 in 10 rows and 5 columns
matrix(rep(1,50),10)
#or in short
matrix(1,10,5)
#in the above short code, both row and column number must
#be mentioned.
#A diagonal matrix of order 4
diag(4)
#or of order 5
diag(5)
#Diagnal elements specified
diag(1:5)
#Matrix with diagonal elements 1,3 & 6
diag(c(1,3,6))
#Suppose x is a matrix. to make vector off its diagonal #elements
x=matrix(9:17,3)
diag(x)
#to make a new matrix using diagonal elements of another #matrix, just give above command a name, say, y.
y=diag(x)
#To make a diagonal matrix using diagonal elements of #another matrix.
z=diag(diag(x))

No comments:
Write comments

Hey, we've a very popular astronomy portal in Bangla language. If You know Bangla, You'll like it - sky.bishwo.com
Join Our Newsletter