Salta ai contenuti. | Salta alla navigazione

Strumenti personali

lab 2&3_vectors and matrix

Plain Text icon Lab 2_vectors and matrix.txt — Plain Text, 2 kB (2301 bytes)

Contenuto del file

MATRIX ALGEBRA 2: LAB USIGN R

CREATION OF A VECTOR: 

v=c(1,2,3,4,5,6,7,8,9) #create a vector called v and composed by 9 elements of numerical nature

we may create a vector using the function seq(min,max,increment): ex

d=seq(1,100,0.5) #create a vector called d composed by 199 numeric elements, from 1.0 to 100.0

we may create a vector defining a priori only the starting number (minimum) and the increment

f=1:10

we may create a vector identifying the min, max and the length
g=seq(-3,-1,length=11)

FUNCTION "REP"
rep(number, n-times) #generally is used to repeat a scheme n times

rep(1,5) #repeat 1, 5 times
[1]1 1 1 1 1 


OPERATIONS USIGN VECTORS

x=c(1,2,3,4)
y=c(2,4,6,8)

x+y #addition of vectors x and y

x-y #subtraction using vectors x and y

x*y #multiplication between vectors x and y

x/y #we divide vector x by y

TRANSPOSE 

t()
t(y) #we create the transpose of y

%*% is a symbol used for a matrix multiplication

t(y)%*%y #row vector multiplied by column vector = a scalar 


-------- TO DO -----------

CREATE x, a vector using 
seq(3,26,1)
length(x) #number of elements in x
max(x) #maximum value in vector x
min(x) #minimum value in vector x
sum(x) #addition of values in x
prod(x) #multiplication of values in x
mean(x) #mean value in vector x
median(x) #median value in vector x
var(x) #sampling variance of vector x

-----------------------------------

CREATE A MATRIX

A=matrix(data=1:30, nrow=5, ncol=6, byrow=FALSE)

#we create a matrix A with data from 1 to 30, with 5 rows and 6 columns 
#by default R create matrix by columns; to invert this command we sould  insert "byrow=TRUE"
#we obtain the same result as: A=matrix(1:30,5,6)

matrix(0,2,3) #matrix of zero with two rows and 3 columns

matrix(,2,3) #matrix composed by 2 rows and 3 columns, without values (NA)

diag(1,3,3) #create a digonal matrix of 1 and dimension 3x3

matrix("Z",2,3) #create a matrix 2 rows and 3 columns of values Z


IDENTIFY ELEMENTS WITHIN A MATRIX

A=matrix(1:30,5,6)
A

A[2,3] #the element (2,3) within the matrix A

A[2,] #second row within the matrix A

A[,2] #second column within the matrix A

which(A>7) #we identify all the elements in A which are greater than 7