1 Matrices and Vectors and Lists

Size: px
Start display at page:

Download "1 Matrices and Vectors and Lists"

Transcription

1 University of Wollongong School of Mathematics and Applied Statistics STAT231 Probability and Random Variables 2014 Second Lab - Week 4 If you can t finish the log-book questions in lab, proceed at home. If you have questions ask your tutor or come to the consultation hours. Be reminded that logbook questions are an assessment task and that future assignments will rely on lab knowledge. 1 Matrices and Vectors and Lists The basic data object in R is a vector. Even scalars are vectors of length 1. There are several ways to create vectors. To create a vector you might use c() operator. The : operator creates sequences incrementing/decrementing by 1. If the step-size should be different, then seq() function can be used. To repeat numbers in a certain fashion you can use rep() by specifying arguments times and each. > b1<-c(0,0,0,1) > #1:n stands for seq(from=1,to=n,by=1) > b2<-1:10 > b3<-10:1 > b4<-seq(from=0,to=10,by=2) > b5<-rep(1:4,times=5) > b6<-rep(1:4,each=2) Matrices are created with the command > matrix(data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL) where the first optional argument is a vector containing the data that is used to fill the matrix, nrow specifies the number of rows and ncol the number of columns. The default option byrow = FALSE is to fill column by column. The matrix multiplication operator in R is %*%. > #matrices > A1<-matrix(c(1,2,3,4,5,6,7,8),nrow=2,ncol=4,byrow=TRUE) > A2<-matrix(c(1,2,3,4,5,6,7,8),nrow=2,ncol=4) #byrow=false > A1>2 > #dimensions of A1 and A2 1

2 > dim(a1) > dim(a2) > #accessing the first row of matrix A1 > A1[1,] > #accessing the second column of matrix A1 > A1[,2] > #multiply matrices > A1%*%A2 #doesn't work because dimensions don't fit > A1%*%t(A2) #so only A1 times transpose of A2 works > #matrix times vector > A1%*%b1 > #or alternatively > A2%*%as.matrix(b1) > #element-wise multiplication > A1*A2 > #row-sum and column-sum > apply(a1,1,sum) > apply(a1,2,sum) A list is a convenient structure to store multiple objects simultaneously. These obsjetcs can be of different type and different length and structure: > n <- c(2, 3, 5) # object 1 > s <- c("aa", "bb", "cc", "dd", "ee") # object 2 > b <- c(true, FALSE, TRUE, FALSE, FALSE) # object 3 > x <- list(n, s, b, 3) # list x contains n, s, b To access the, say, first element and second element of a list you use double brackets [[]] : > x[[1]] [1] > x[[2]] [1] "aa" "bb" "cc" "dd" "ee" 2

3 You can also name elements and then refer to the name > # list x contains n, s, b, now named "n", "s" and "b.vector" > x <- list(n=n,s=s,b.vector=b,number=3) > # option 1: using the entry number > x[[1]] [1] > x[[3]] [1] TRUE FALSE TRUE FALSE FALSE > #option 2: using element's name > x$n [1] > x$b.vector [1] TRUE FALSE TRUE FALSE FALSE Do you remember the data-frame object from the lab of week 1? A dataframe has properties of a matrix and of a list. You can access the elements of the dataframe in the same way as with lists by calling its column name, but also by using the matrix notation that is used to access, say, the columns of a matrix. There is one fundamental difference between lists and dataframes. Each column/object of a dataframe needs to have the same length. A list doesn t have this requirement. A dataframe can also be easily converted into a matrix (if dataframe consists of numbers for example) using the command as.matrix(). 2 Some Control Structures in R 2.1 Loops R has a several types of loops, for example the for and while-loops. Examples are given below when computing the product of the numbers 1 to 10. > #loops > #for loop > f<-1 3

4 > index<-1:10 > #"for" loop executed as many times as length of index and > # i takes values of the index-set "index" > for(i in index){ + f<-f*i + #cat is here to produce output of current values of f + cat("current value of f at ",i,"th iteration: ",f,"\n") + } current value of f at 1 th iteration: 1 current value of f at 2 th iteration: 2 current value of f at 3 th iteration: 6 current value of f at 4 th iteration: 24 current value of f at 5 th iteration: 120 current value of f at 6 th iteration: 720 current value of f at 7 th iteration: 5040 current value of f at 8 th iteration: current value of f at 9 th iteration: current value of f at 10 th iteration: > f [1] > #while loop > f<-1 > i<-1 > while(i<=10){ + #executes the statements that follow until + # condition not met, here as long as i<= f<-f*i + cat("current value of f at ",i,"th iteration: ",f,"\n") + i<-i+1 + } current value of f at 1 th iteration: 1 current value of f at 2 th iteration: 2 current value of f at 3 th iteration: 6 current value of f at 4 th iteration: 24 current value of f at 5 th iteration: 120 current value of f at 6 th iteration: 720 current value of f at 7 th iteration: 5040 current value of f at 8 th iteration:

5 current value of f at 9 th iteration: current value of f at 10 th iteration: > f [1] > #easier > prod(1:10) [1] If/Then Statement The if/then statement in R has the following form. > if(cond){ + #evaluate expression if cond is true + }else{ + #evaluate expression if cond is false + } Alternatively you can use ifthen(cond,expr.true,expr.false). > x<-5 > if(x<0){cat("number <0\n")}else{cat("Number >=0\n")} Number >=0 > x<--3 > if(x<0){cat("number <0\n")}else{cat("Number >=0\n")} Number <0 > x <- c(6:-4) > for(i in x){ + ifelse(i >= 0, print(sqrt(i)), print(na)) + } [1] [1] [1] 2 5

6 [1] [1] [1] 1 [1] 0 [1] NA [1] NA [1] NA [1] NA 3 Functions Sometimes we want to calculate or apply an operation to many numbers or repeat an analysis which consist of many lines of code. In this case it is often easier to define functions that contain this complex code. When a function is defined we need to allocate a name. Once it is defined, the name can be applied to several data sets by only calling the name of the function and its arguments without needing to repeat numerous times the possibly lengthy code. > myfunction <- function(arg1, arg2,... ){ + statements + return(object) + } Here myfunction is an arbitrary chosen name, and arg1, arg2,... are arguments of the function. The definition needs to finish with returning of an object, here achieved by return(object). In Section 2.1 we calculated the product of the first 10 number, in fact that s the factorial function, in r implemented by factorial(). To illustrate functions in R we define the factorial functions in several ways. > factorial1<-function(n){return(prod(1:n))} > factorial2<-function(n){prod(1:n)} #without using return > # since prod(1:n) shows an output when entered in R console, it > # returns this output automatically without using return() > # to be "cleaner", using "return" is recommended > > #factorial3 calls itself, called recursion > factorial3<-function(n){ + cat("n=",n,"\n"); 6

7 + if(n==1){ + return(n) + }else{ + return(n*factorial3(n-1)) + }#end if + }#end function factorial 3 Now test by yourself and try to understand why and how these functions work! > #tests > factorial1(10) > factorial2(10) > factorial3(10) > factorial1(15) > factorial2(15) > factorial3(15) > #compare with default R-function > factorial(10) > factorial(15) In R you can only return one object not several. For example if you have a data set and you want to return ȳ and s 2, you need to set-up a list which then contains these two values as elements. > y<-seq(1,100,by=2) > bary.s2<-function(data){ + meany<-mean(data); + vary<-var(data) + list1<-list(bary=meany,s2=vary) #first element is called bary, 2nd s2 + return(list1) + } > #now apply function to data "y" > bary.s2(data=y) $bary [1] 50 $s2 [1] 850 7

8 > #or storing > test<-bary.s2(y) > #show bary=sample mean > test$bary [1] 50 > #show s2=sample var > test$s2 [1] 850 > #directly > mean(y) [1] 50 > var(y) [1] Hypergeometric Distribution Create the probability function (p.f.) f(y) and the cumulative distribution function (c.d.f.) F (y) for the hypergeometric distribution with parameters N = 42, K = 7,n = 21 with (notations from lecture). Recall (in case this has already been covered) that N is the population size, n the size of sample taken (sample size), and K is the number of objects with certain characteristic (e.g. white balls). First create a sequence of numbers from 0 to 7, the domain of Y. The R-function dhyper (p.f. of hypergeometric) uses different notations for parameters: > y<-0:7 #y<-sequence(0,7,by=1) > # m is the number of while balls (what we call K) > # n the number of black balls, therefore N=m+n and m=n-n > # k=21 (what we call usually n) > # The probability function in R gives > # the probability of having x while balls! > fy<- dhyper(x=y, m=7, n=42-7, k=21) 8

9 The Vector fy contains the 8 probabilities when referring to the events that the sample contains 0, 1,..., 7 white balls. Calculate the c.d.f. using cumsum(), a function for the cumulative sum, see help(cumsum): > FY<-cumsum(fY) > #alternatively use > FY1<-phyper(q=y, m=7, n=42-7, k=21) > #compare FY with FY1 > FY-FY1 [1] e e e e e-16 [6] e e e-16 Some plotting: > #first plain plots > plot(0:7,fy) > points(0:7,fy) > #doesn't look good fy :7 This looks rather non-informative, instead we draw lines using a histogram style, a stepfunction style and some coloring. > plot(0:7,fy,type="h",col="red",ylim=c(0,1)) #histogram type > points(0:7,fy,type="s",lty=1,col="blue") #step type > # needs legend, where you need to define also colors and line-type (lty) > legend("topleft",c("f(y)","f(y)"),col=c("red","blue"),lty=c(1,1)) 9

10 fy f(y) F(y) :7 There are many graphical parameters for functions like plot(), points(), lines(), etc. to enable changing almost every aspect of a plot, which makes R very powerful, but sometimes this is complicated finding the correct parameters for the desired outcome. 5 Simulating Random Numbers Before we continue enter > set.seed(studentid) where studentid is your actual UOW student ID. This command will ensure that every student creates unique random numbers, which guarantees that all of you have different results of your log-book questions. We first generate 150 random numbers from the uniform distribution in [0, 1]. Then we transform the data and obtain a vector Y1, which contains random numbers 0, 1,..., 7, in fact numbers from the hypergeometric distribution described above, achieved by the transformation inside the for-loop. > size<-150 > U<-runif(size) > Y1<-rep(0,size) > for(i in 1:size){ + Y1[i]<- min((0:7)[u[i]<=fy]) + }#end for loop > #to check what happens fix i, e.g. i<-10 10

11 > # enter 1) U[i], 2) FY, 3) U[i]<=FY > # then 4) (0:7)[U[i]<=FY] > > #simpler is to use R command > Y2<-rhyper(nn=size, m=7, n=42-7, k=21) > # Plot the histograms > hist(y1,breaks=seq(-0.5,7.5,by=1)) > hist(y2,breaks=seq(-0.5,7.5,by=1)) Histogram of Y1 Histogram of Y2 Frequency Frequency Y Y2 Next we use the simulated data to estimate the mean, the variance, P (Y = 3), P (2 Y 4) and P (1 Y 6) with the R-functions mean(), var(). > mean(y1) > mean(y2) > var(y1) > var(y2) > # Find > #P(Y=3) > Y1==3 #look at output and compare with Y1 > mean(y1==3) # sum(y1==3)/150 11

12 > mean(y2==3) # sum(y2==3)/150 > #P(2<=Y<=4) > Y1>=2 & Y1<=4 #look at output and compare with Y1 > mean(y1>=2 & Y1<=4) > mean(y2>=2 & Y2<=4) > #P(1<=Y<=6) > Y1>=1 & Y1<=6 #look at output and compare with Y1 > mean(y1>=1 & Y1<=6) > mean(y2>=1 & Y2<=6) To calculate an estimate for P (Y = 3), we first simulate the random numbers stored in Y1, then we check whether each number equals 3 by Y1==3, which results in a vector of size 150 of Boolean-type (TRUE/FALSE). Then the mean()-function is applied to this vector, however TRUE is converted to 1 and FALSE is converted to 0, hence mean() is applied to a vector of 1 s and 0 s. It counts the average proportion of observing a 3, which is an estimate for the probability of observing a 3. 12

Introduction to R Forecasting Techniques

Introduction to R Forecasting Techniques Introduction to R zabbeta@fsu.gr katerina@fsu.gr Starting out in R Working with data Plotting & Forecasting 1. Starting Out In R R & RStudio Variables & Basics Data Types Functions R + RStudio Programming

More information

Matrix algebra. Basics

Matrix algebra. Basics Matrix.1 Matrix algebra Matrix algebra is very prevalently used in Statistics because it provides representations of models and computations in a much simpler manner than without its use. The purpose of

More information

Logical operators: R provides an extensive list of logical operators. These include

Logical operators: R provides an extensive list of logical operators. These include meat.r: Explanation of code Goals of code: Analyzing a subset of data Creating data frames with specified X values Calculating confidence and prediction intervals Lists and matrices Only printing a few

More information

LAB #2: SAMPLING, SAMPLING DISTRIBUTIONS, AND THE CLT

LAB #2: SAMPLING, SAMPLING DISTRIBUTIONS, AND THE CLT NAVAL POSTGRADUATE SCHOOL LAB #2: SAMPLING, SAMPLING DISTRIBUTIONS, AND THE CLT Statistics (OA3102) Lab #2: Sampling, Sampling Distributions, and the Central Limit Theorem Goal: Use R to demonstrate sampling

More information

Armstrong State University Engineering Studies MATLAB Marina 2D Arrays and Matrices Primer

Armstrong State University Engineering Studies MATLAB Marina 2D Arrays and Matrices Primer Armstrong State University Engineering Studies MATLAB Marina 2D Arrays and Matrices Primer Prerequisites The 2D Arrays and Matrices Primer assumes knowledge of the MATLAB IDE, MATLAB help, arithmetic operations,

More information

Stat 579: Objects in R Vectors

Stat 579: Objects in R Vectors Stat 579: Objects in R Vectors Ranjan Maitra 2220 Snedecor Hall Department of Statistics Iowa State University. Phone: 515-294-7757 maitra@iastate.edu, 1/23 Logical Vectors I R allows manipulation of logical

More information

Description/History Objects/Language Description Commonly Used Basic Functions. More Specific Functionality Further Resources

Description/History Objects/Language Description Commonly Used Basic Functions. More Specific Functionality Further Resources R Outline Description/History Objects/Language Description Commonly Used Basic Functions Basic Stats and distributions I/O Plotting Programming More Specific Functionality Further Resources www.r-project.org

More information

Lecture 3: Basics of R Programming

Lecture 3: Basics of R Programming Lecture 3: Basics of R Programming This lecture introduces you to how to do more things with R beyond simple commands. Outline: 1. R as a programming language 2. Grouping, loops and conditional execution

More information

Lecture 3: Basics of R Programming

Lecture 3: Basics of R Programming Lecture 3: Basics of R Programming This lecture introduces how to do things with R beyond simple commands. We will explore programming in R. What is programming? It is the act of instructing a computer

More information

Matlab notes Matlab is a matrix-based, high-performance language for technical computing It integrates computation, visualisation and programming usin

Matlab notes Matlab is a matrix-based, high-performance language for technical computing It integrates computation, visualisation and programming usin Matlab notes Matlab is a matrix-based, high-performance language for technical computing It integrates computation, visualisation and programming using familiar mathematical notation The name Matlab stands

More information

An introduction to R WS 2013/2014

An introduction to R WS 2013/2014 An introduction to R WS 2013/2014 Dr. Noémie Becker (AG Metzler) Dr. Sonja Grath (AG Parsch) Special thanks to: Dr. Martin Hutzenthaler (previously AG Metzler, now University of Frankfurt) course development,

More information

Objectives of This Chapter

Objectives of This Chapter Chapter 6 C Arrays Objectives of This Chapter Array data structures to represent the set of values. Defining and initializing arrays. Defining symbolic constant in a program. Using arrays to store, list,

More information

6.001 Notes: Section 8.1

6.001 Notes: Section 8.1 6.001 Notes: Section 8.1 Slide 8.1.1 In this lecture we are going to introduce a new data type, specifically to deal with symbols. This may sound a bit odd, but if you step back, you may realize that everything

More information

MATLAB Basics. Configure a MATLAB Package 6/7/2017. Stanley Liang, PhD York University. Get a MATLAB Student License on Matworks

MATLAB Basics. Configure a MATLAB Package 6/7/2017. Stanley Liang, PhD York University. Get a MATLAB Student License on Matworks MATLAB Basics Stanley Liang, PhD York University Configure a MATLAB Package Get a MATLAB Student License on Matworks Visit MathWorks at https://www.mathworks.com/ It is recommended signing up with a student

More information

6.001 Notes: Section 4.1

6.001 Notes: Section 4.1 6.001 Notes: Section 4.1 Slide 4.1.1 In this lecture, we are going to take a careful look at the kinds of procedures we can build. We will first go back to look very carefully at the substitution model,

More information

Statistical Computing (36-350)

Statistical Computing (36-350) Statistical Computing (36-350) Lecture 1: Introduction to the course; Data Cosma Shalizi and Vincent Vu 29 August 2011 Why good statisticians learn how to program Independence: otherwise, you rely on someone

More information

R:If, else and loops

R:If, else and loops R:If, else and loops Presenter: Georgiana Onicescu January 19, 2012 Presenter: Georgiana Onicescu R:ifelse,where,looping 1/ 17 Contents Vectors Matrices If else statements For loops Leaving the loop: stop,

More information

MBV4410/9410 Fall Bioinformatics for Molecular Biology. Introduction to R

MBV4410/9410 Fall Bioinformatics for Molecular Biology. Introduction to R MBV4410/9410 Fall 2018 Bioinformatics for Molecular Biology Introduction to R Outline Introduce R Basic operations RStudio Bioconductor? Goal of the lecture Introduce you to R Show how to run R, basic

More information

More Complicated Recursion CMPSC 122

More Complicated Recursion CMPSC 122 More Complicated Recursion CMPSC 122 Now that we've gotten a taste of recursion, we'll look at several more examples of recursion that are special in their own way. I. Example with More Involved Arithmetic

More information

EPIB Four Lecture Overview of R

EPIB Four Lecture Overview of R EPIB-613 - Four Lecture Overview of R R is a package with enormous capacity for complex statistical analysis. We will see only a small proportion of what it can do. The R component of EPIB-613 is divided

More information

Constraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial

Constraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial 1 Matlab Tutorial 2 Lecture Learning Objectives Each student should be able to: Describe the Matlab desktop Explain the basic use of Matlab variables Explain the basic use of Matlab scripts Explain the

More information

Essentials for the TI-83+

Essentials for the TI-83+ Essentials for the TI-83+ Special Keys. O S O O Press and release, then press the appropriate key to access the 2nd (yellow) operation. Press and release to access characters and letters indicated above

More information

Loopy stuff: for loops

Loopy stuff: for loops R Programming Week 3 : Intro to Loops Reminder: Some of the exercises below require you to have mastered (1) the use of the cat function, and (2) the use of the source function. Loopy stuff: for loops

More information

MAT 275 Laboratory 2 Matrix Computations and Programming in MATLAB

MAT 275 Laboratory 2 Matrix Computations and Programming in MATLAB MATLAB sessions: Laboratory MAT 75 Laboratory Matrix Computations and Programming in MATLAB In this laboratory session we will learn how to. Create and manipulate matrices and vectors.. Write simple programs

More information

EN 001-4: Introduction to Computational Design. Matrices & vectors. Why do we care about vectors? What is a matrix and a vector?

EN 001-4: Introduction to Computational Design. Matrices & vectors. Why do we care about vectors? What is a matrix and a vector? EN 001-: Introduction to Computational Design Fall 2017 Tufts University Instructor: Soha Hassoun soha@cs.tufts.edu Matrices & vectors Matlab is short for MATrix LABoratory. In Matlab, pretty much everything

More information

ENGG1811 Computing for Engineers Week 10 Matlab: Vectorization. (No loops, please!)

ENGG1811 Computing for Engineers Week 10 Matlab: Vectorization. (No loops, please!) ENGG1811 Computing for Engineers Week 10 Matlab: Vectorization. (No loops, please!) ENGG1811 UNSW, CRICOS Provider No: 00098G1 W10 slide 1 Vectorisation Matlab is designed to work with vectors and matrices

More information

Lab 4 CSE 7, Spring 2018 This lab is an introduction to using logical and comparison operators in Matlab.

Lab 4 CSE 7, Spring 2018 This lab is an introduction to using logical and comparison operators in Matlab. LEARNING OBJECTIVES: Lab 4 CSE 7, Spring 2018 This lab is an introduction to using logical and comparison operators in Matlab 1 Use comparison operators (< > = == ~=) between two scalar values to create

More information

Introduction to R. UCLA Statistical Consulting Center R Bootcamp. Irina Kukuyeva September 20, 2010

Introduction to R. UCLA Statistical Consulting Center R Bootcamp. Irina Kukuyeva September 20, 2010 UCLA Statistical Consulting Center R Bootcamp Irina Kukuyeva ikukuyeva@stat.ucla.edu September 20, 2010 Outline 1 Introduction 2 Preliminaries 3 Working with Vectors and Matrices 4 Data Sets in R 5 Overview

More information

Statistical Programming Worksheet 4

Statistical Programming Worksheet 4 Statistical Programming Worksheet 4 1. Cholesky Decomposition. (a) Write a function with argument n to generate a random symmetric n n-positive definite matrix. To do this: generate an n n matrix C whose

More information

CS1114: Matlab Introduction

CS1114: Matlab Introduction CS1114: Matlab Introduction 1 Introduction The purpose of this introduction is to provide you a brief introduction to the features of Matlab that will be most relevant to your work in this course. Even

More information

Team Prob. Team Prob

Team Prob. Team Prob 1 Introduction In this module, we will be simulating the draft lottery used by the National Basketball Association (NBA). Each year, the worst 14 teams are entered into a drawing to determine who will

More information

Matrices. Chapter Matrix A Mathematical Definition Matrix Dimensions and Notation

Matrices. Chapter Matrix A Mathematical Definition Matrix Dimensions and Notation Chapter 7 Introduction to Matrices This chapter introduces the theory and application of matrices. It is divided into two main sections. Section 7.1 discusses some of the basic properties and operations

More information

CS1114: Matlab Introduction

CS1114: Matlab Introduction CS1114: Matlab Introduction 1 Introduction The purpose of this introduction is to provide you a brief introduction to the features of Matlab that will be most relevant to your work in this course. Even

More information

A Brief Introduction to R

A Brief Introduction to R A Brief Introduction to R Babak Shahbaba Department of Statistics, University of California, Irvine, USA Chapter 1 Introduction to R 1.1 Installing R To install R, follow these steps: 1. Go to http://www.r-project.org/.

More information

Basic matrix math in R

Basic matrix math in R 1 Basic matrix math in R This chapter reviews the basic matrix math operations that you will need to understand the course material and how to do these operations in R. 1.1 Creating matrices in R Create

More information

ECE 2574: Data Structures and Algorithms - Recursion Part I. C. L. Wyatt

ECE 2574: Data Structures and Algorithms - Recursion Part I. C. L. Wyatt ECE 2574: Data Structures and Algorithms - Recursion Part I C. L. Wyatt Today we will introduce the notion of recursion, look at some examples, and see how to implement them in code. Introduction to recursion

More information

Statistical Computing (36-350)

Statistical Computing (36-350) Statistical Computing (36-350) Lecture 3: Flow Control Cosma Shalizi and Vincent Vu 7 September 2011 Agenda Conditionals: Switching between doing different things Iteration: Doing similar things many times

More information

Introduction to Matlab

Introduction to Matlab Introduction to Matlab Andreas C. Kapourani (Credit: Steve Renals & Iain Murray) 9 January 08 Introduction MATLAB is a programming language that grew out of the need to process matrices. It is used extensively

More information

It can be confusing when you type something like the expressions below and get an error message. a range variable definition a vector of sine values

It can be confusing when you type something like the expressions below and get an error message. a range variable definition a vector of sine values 7_april_ranges_.mcd Understanding Ranges, Sequences, and Vectors Introduction New Mathcad users are sometimes confused by the difference between range variables and vectors. This is particularly true considering

More information

Introduction to Octave/Matlab. Deployment of Telecommunication Infrastructures

Introduction to Octave/Matlab. Deployment of Telecommunication Infrastructures Introduction to Octave/Matlab Deployment of Telecommunication Infrastructures 1 What is Octave? Software for numerical computations and graphics Particularly designed for matrix computations Solving equations,

More information

Lecture 15 MATLAB II: Conditional Statements and Arrays

Lecture 15 MATLAB II: Conditional Statements and Arrays Lecture 15 MATLAB II: Conditional Statements and Arrays 1 Conditional Statements 2 The boolean operators in MATLAB are: > greater than < less than >= greater than or equals

More information

Introduction to R gherardo varando

Introduction to R gherardo varando Introduction to R gherardo varando The R Software Environment As The R Project website states : and R is a free software environment for statistical computing and graphics. It compiles and runs on a wide

More information

Vectors and Matrices. Chapter 2. Linguaggio Programmazione Matlab-Simulink (2017/2018)

Vectors and Matrices. Chapter 2. Linguaggio Programmazione Matlab-Simulink (2017/2018) Vectors and Matrices Chapter 2 Linguaggio Programmazione Matlab-Simulink (2017/2018) Matrices A matrix is used to store a set of values of the same type; every value is stored in an element MATLAB stands

More information

Control Flow Structures

Control Flow Structures Control Flow Structures STAT 133 Gaston Sanchez Department of Statistics, UC Berkeley gastonsanchez.com github.com/gastonstat/stat133 Course web: gastonsanchez.com/stat133 Expressions 2 Expressions R code

More information

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.! True object-oriented programming: Dynamic Objects Reference Variables D0010E Object-Oriented Programming and Design Lecture 3 Static Object-Oriented Programming UML" knows-about Eckel: 30-31, 41-46, 107-111,

More information

CSCI 520 Homework 8. Megan Rose Bryant Department of Mathematics William and Mary

CSCI 520 Homework 8. Megan Rose Bryant Department of Mathematics William and Mary CSCI 520 Homework 8 Megan Rose Bryant Department of Mathematics William and Mary October 29, 2014 1. Identify any typographical errors or suggestions in the first 22 chapters of the R book. Here is a sample

More information

Overview. Linear Algebra Notation. MATLAB Data Types Data Visualization. Probability Review Exercises. Asymptotics (Big-O) Review

Overview. Linear Algebra Notation. MATLAB Data Types Data Visualization. Probability Review Exercises. Asymptotics (Big-O) Review Tutorial 1 1 / 21 Overview Linear Algebra Notation Data Types Data Visualization Probability Review Exercises Asymptotics (Big-O) Review 2 / 21 Linear Algebra Notation Notation and Convention 3 / 21 Linear

More information

1 Pencil and Paper stuff

1 Pencil and Paper stuff Spring 2008 - Stat C141/ Bioeng C141 - Statistics for Bioinformatics Course Website: http://www.stat.berkeley.edu/users/hhuang/141c-2008.html Section Website: http://www.stat.berkeley.edu/users/mgoldman

More information

Vectors and Matrices Flow Control Plotting Functions Simulating Systems Installing Packages Getting Help Assignments. R Tutorial

Vectors and Matrices Flow Control Plotting Functions Simulating Systems Installing Packages Getting Help Assignments. R Tutorial R Tutorial Anup Aprem aaprem@ece.ubc.ca September 14, 2017 Installation Installing R: https://www.r-project.org/ Recommended to also install R Studio: https://www.rstudio.com/ Vectors Basic element is

More information

II.Matrix. Creates matrix, takes a vector argument and turns it into a matrix matrix(data, nrow, ncol, byrow = F)

II.Matrix. Creates matrix, takes a vector argument and turns it into a matrix matrix(data, nrow, ncol, byrow = F) II.Matrix A matrix is a two dimensional array, it consists of elements of the same type and displayed in rectangular form. The first index denotes the row; the second index denotes the column of the specified

More information

Functions and data structures. Programming in R for Data Science Anders Stockmarr, Kasper Kristensen, Anders Nielsen

Functions and data structures. Programming in R for Data Science Anders Stockmarr, Kasper Kristensen, Anders Nielsen Functions and data structures Programming in R for Data Science Anders Stockmarr, Kasper Kristensen, Anders Nielsen Objects of the game In R we have objects which are functions and objects which are data.

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

Extremely short introduction to R Jean-Yves Sgro Feb 20, 2018

Extremely short introduction to R Jean-Yves Sgro Feb 20, 2018 Extremely short introduction to R Jean-Yves Sgro Feb 20, 2018 Contents 1 Suggested ahead activities 1 2 Introduction to R 2 2.1 Learning Objectives......................................... 2 3 Starting

More information

CSCE 110 PROGRAMMING FUNDAMENTALS. Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays

CSCE 110 PROGRAMMING FUNDAMENTALS. Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays Prof. Amr Goneid, AUC 1 Arrays Prof. Amr Goneid, AUC 2 1-D Arrays Data Structures The Array Data Type How to Declare

More information

OUTLINES. Variable names in MATLAB. Matrices, Vectors and Scalar. Entering a vector Colon operator ( : ) Mathematical operations on vectors.

OUTLINES. Variable names in MATLAB. Matrices, Vectors and Scalar. Entering a vector Colon operator ( : ) Mathematical operations on vectors. 1 LECTURE 3 OUTLINES Variable names in MATLAB Examples Matrices, Vectors and Scalar Scalar Vectors Entering a vector Colon operator ( : ) Mathematical operations on vectors examples 2 VARIABLE NAMES IN

More information

GS Analysis of Microarray Data

GS Analysis of Microarray Data GS01 0163 Analysis of Microarray Data Keith Baggerly and Kevin Coombes Section of Bioinformatics Department of Biostatistics and Applied Mathematics UT M. D. Anderson Cancer Center kabagg@mdanderson.org

More information

Probability and Statistics for Final Year Engineering Students

Probability and Statistics for Final Year Engineering Students Probability and Statistics for Final Year Engineering Students By Yoni Nazarathy, Last Updated: April 11, 2011. Lecture 1: Introduction and Basic Terms Welcome to the course, time table, assessment, etc..

More information

R Tutorial. Anup Aprem September 13, 2016

R Tutorial. Anup Aprem September 13, 2016 R Tutorial Anup Aprem aaprem@ece.ubc.ca September 13, 2016 Installation Installing R: https://www.r-project.org/ Recommended to also install R Studio: https://www.rstudio.com/ Vectors Basic element is

More information

CS 61A, Fall, 2002, Midterm #2, L. Rowe. 1. (10 points, 1 point each part) Consider the following five box-and-arrow diagrams.

CS 61A, Fall, 2002, Midterm #2, L. Rowe. 1. (10 points, 1 point each part) Consider the following five box-and-arrow diagrams. CS 61A, Fall, 2002, Midterm #2, L. Rowe 1. (10 points, 1 point each part) Consider the following five box-and-arrow diagrams. a) d) 3 1 2 3 1 2 e) b) 3 c) 1 2 3 1 2 1 2 For each of the following Scheme

More information

Short Introduction to Python Machine Learning Course Laboratory

Short Introduction to Python Machine Learning Course Laboratory Pattern Recognition and Applications Lab Short Introduction to Python Machine Learning Course Laboratory Battista Biggio battista.biggio@diee.unica.it Luca Didaci didaci@diee.unica.it Dept. Of Electrical

More information

R basics workshop Sohee Kang

R basics workshop Sohee Kang R basics workshop Sohee Kang Math and Stats Learning Centre Department of Computer and Mathematical Sciences Objective To teach the basic knowledge necessary to use R independently, thus helping participants

More information

MAT 275 Laboratory 2 Matrix Computations and Programming in MATLAB

MAT 275 Laboratory 2 Matrix Computations and Programming in MATLAB MAT 75 Laboratory Matrix Computations and Programming in MATLAB In this laboratory session we will learn how to. Create and manipulate matrices and vectors.. Write simple programs in MATLAB NOTE: For your

More information

Data Structures STAT 133. Gaston Sanchez. Department of Statistics, UC Berkeley

Data Structures STAT 133. Gaston Sanchez. Department of Statistics, UC Berkeley Data Structures STAT 133 Gaston Sanchez Department of Statistics, UC Berkeley gastonsanchez.com github.com/gastonstat/stat133 Course web: gastonsanchez.com/stat133 Data Types and Structures To make the

More information

CS100R: Matlab Introduction

CS100R: Matlab Introduction CS100R: Matlab Introduction August 25, 2007 1 Introduction The purpose of this introduction is to provide you a brief introduction to the features of Matlab that will be most relevant to your work in this

More information

Probability Models.S4 Simulating Random Variables

Probability Models.S4 Simulating Random Variables Operations Research Models and Methods Paul A. Jensen and Jonathan F. Bard Probability Models.S4 Simulating Random Variables In the fashion of the last several sections, we will often create probability

More information

INTRODUCTION TO MATLAB, SIMULINK, AND THE COMMUNICATION TOOLBOX

INTRODUCTION TO MATLAB, SIMULINK, AND THE COMMUNICATION TOOLBOX INTRODUCTION TO MATLAB, SIMULINK, AND THE COMMUNICATION TOOLBOX 1) Objective The objective of this lab is to review how to access Matlab, Simulink, and the Communications Toolbox, and to become familiar

More information

Matrices. A Matrix (This one has 2 Rows and 3 Columns) To add two matrices: add the numbers in the matching positions:

Matrices. A Matrix (This one has 2 Rows and 3 Columns) To add two matrices: add the numbers in the matching positions: Matrices A Matrix is an array of numbers: We talk about one matrix, or several matrices. There are many things we can do with them... Adding A Matrix (This one has 2 Rows and 3 Columns) To add two matrices:

More information

Advanced Data Analysis 1 Stat 427/527

Advanced Data Analysis 1 Stat 427/527 Advanced Data Analysis 1 Stat 427/527 Chapter 00-2 R building blocks Erik B. Erhardt Department of Mathematics and Statistics MSC01 1115 1 University of New Mexico Albuquerque, New Mexico, 87131-0001 Office:

More information

Introduction to scientific programming in R

Introduction to scientific programming in R Introduction to scientific programming in R John M. Drake & Pejman Rohani 1 Introduction This course will use the R language programming environment for computer modeling. The purpose of this exercise

More information

R (and S, and S-Plus, another program based on S) is an interactive, interpretive, function language.

R (and S, and S-Plus, another program based on S) is an interactive, interpretive, function language. R R (and S, and S-Plus, another program based on S) is an interactive, interpretive, function language. Available on Linux, Unix, Mac, and MS Windows systems. Documentation exists in several volumes, and

More information

Lab #10 Multi-dimensional Arrays

Lab #10 Multi-dimensional Arrays Multi-dimensional Arrays Sheet s Owner Student ID Name Signature Group partner 1. Two-Dimensional Arrays Arrays that we have seen and used so far are one dimensional arrays, where each element is indexed

More information

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration STATS 507 Data Analysis in Python Lecture 2: Functions, Conditionals, Recursion and Iteration Functions in Python We ve already seen examples of functions: e.g., type()and print() Function calls take the

More information

ITS Introduction to R course

ITS Introduction to R course ITS Introduction to R course Nov. 29, 2018 Using this document Code blocks and R code have a grey background (note, code nested in the text is not highlighted in the pdf version of this document but is

More information

Spatial Ecology Lab 8: Control Structures

Spatial Ecology Lab 8: Control Structures Spatial Ecology Lab 8: Control Structures Damian Maddalena Spring 2015 1 Introduction This week in lab, we will look at methods to direct the flow of operations in your code. There are several methods

More information

Therefore, after becoming familiar with the Matrix Method, you will be able to solve a system of two linear equations in four different ways.

Therefore, after becoming familiar with the Matrix Method, you will be able to solve a system of two linear equations in four different ways. Grade 9 IGCSE A1: Chapter 9 Matrices and Transformations Materials Needed: Straightedge, Graph Paper Exercise 1: Matrix Operations Matrices are used in Linear Algebra to solve systems of linear equations.

More information

A (very) short introduction to R

A (very) short introduction to R A (very) short introduction to R Paul Torfs & Claudia Brauer Hydrology and Quantitative Water Management Group Wageningen University, The Netherlands 1 Introduction 16 April 2012 R is a powerful language

More information

ENGR 1181 MATLAB 02: Array Creation

ENGR 1181 MATLAB 02: Array Creation ENGR 1181 MATLAB 02: Array Creation Learning Objectives: Students will read Chapter 2.1 2.4 of the MATLAB book before coming to class. This preparation material is provided to supplement this reading.

More information

Functional Programming. Contents

Functional Programming. Contents Functional Programming Gunnar Gotshalks 2003 September 27 Contents Introduction... 2 Example for Inner Product... 2 Basis Set for Functionals... 3 Example Function Definitions... 3 Lisp Builtin Functionals...

More information

ESC101 : Fundamental of Computing

ESC101 : Fundamental of Computing ESC101 : Fundamental of Computing End Semester Exam 19 November 2008 Name : Roll No. : Section : Note : Read the instructions carefully 1. You will lose 3 marks if you forget to write your name, roll number,

More information

User-defined Functions. Conditional Expressions in Scheme

User-defined Functions. Conditional Expressions in Scheme User-defined Functions The list (lambda (args (body s to a function with (args as its argument list and (body as the function body. No quotes are needed for (args or (body. (lambda (x (+ x 1 s to the increment

More information

Physics 2660: Fundamentals of Scientific Computing. Lecture 7 Instructor: Prof. Chris Neu

Physics 2660: Fundamentals of Scientific Computing. Lecture 7 Instructor: Prof. Chris Neu Physics 2660: Fundamentals of Scientific Computing Lecture 7 Instructor: Prof. Chris Neu (chris.neu@virginia.edu) Reminder HW06 due Thursday 15 March electronically by noon HW grades are starting to appear!

More information

EL2310 Scientific Programming

EL2310 Scientific Programming (pronobis@kth.se) Overview Overview Wrap Up More on Scripts and Functions Basic Programming Lecture 2 Lecture 3 Lecture 4 Wrap Up Last time Loading data from file: load( filename ) Graphical input and

More information

Mathematical Induction

Mathematical Induction Mathematical Induction Victor Adamchik Fall of 2005 Lecture 3 (out of three) Plan 1. Recursive Definitions 2. Recursively Defined Sets 3. Program Correctness Recursive Definitions Sometimes it is easier

More information

What is MATLAB? What is MATLAB? Programming Environment MATLAB PROGRAMMING. Stands for MATrix LABoratory. A programming environment

What is MATLAB? What is MATLAB? Programming Environment MATLAB PROGRAMMING. Stands for MATrix LABoratory. A programming environment What is MATLAB? MATLAB PROGRAMMING Stands for MATrix LABoratory A software built around vectors and matrices A great tool for numerical computation of mathematical problems, such as Calculus Has powerful

More information

Statistical Programming with R

Statistical Programming with R Statistical Programming with R Lecture 6: Programming Examples Bisher M. Iqelan biqelan@iugaza.edu.ps Department of Mathematics, Faculty of Science, The Islamic University of Gaza 2017-2018, Semester 1

More information

Module 3: New types of data

Module 3: New types of data Module 3: New types of data Readings: Sections 4 and 5 of HtDP. A Racket program applies functions to values to compute new values. These new values may in turn be supplied as arguments to other functions.

More information

Case by Case. Chapter 3

Case by Case. Chapter 3 Chapter 3 Case by Case In the previous chapter, we used the conditional expression if... then... else to define functions whose results depend on their arguments. For some of them we had to nest the conditional

More information

Getting started with MATLAB

Getting started with MATLAB Getting started with MATLAB You can work through this tutorial in the computer classes over the first 2 weeks, or in your own time. The Farber and Goldfarb computer classrooms have working Matlab, but

More information

Package listdtr. November 29, 2016

Package listdtr. November 29, 2016 Package listdtr November 29, 2016 Type Package Title List-Based Rules for Dynamic Treatment Regimes Version 1.0 Date 2016-11-20 Author Yichi Zhang Maintainer Yichi Zhang Construction

More information

LAB 2 VECTORS AND MATRICES

LAB 2 VECTORS AND MATRICES EN001-4: Intro to Computational Design Tufts University, Department of Computer Science Prof. Soha Hassoun LAB 2 VECTORS AND MATRICES 1.1 Background Overview of data types Programming languages distinguish

More information

Lecture 57 Dynamic Programming. (Refer Slide Time: 00:31)

Lecture 57 Dynamic Programming. (Refer Slide Time: 00:31) Programming, Data Structures and Algorithms Prof. N.S. Narayanaswamy Department of Computer Science and Engineering Indian Institution Technology, Madras Lecture 57 Dynamic Programming (Refer Slide Time:

More information

Organization of Programming Languages CS3200/5200N. Lecture 11

Organization of Programming Languages CS3200/5200N. Lecture 11 Organization of Programming Languages CS3200/5200N Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.edu Functional vs. Imperative The design of the imperative languages

More information

Resources matter. Orders of Growth of Processes. R(n)= (n 2 ) Orders of growth of processes. Partial trace for (ifact 4) Partial trace for (fact 4)

Resources matter. Orders of Growth of Processes. R(n)= (n 2 ) Orders of growth of processes. Partial trace for (ifact 4) Partial trace for (fact 4) Orders of Growth of Processes Today s topics Resources used by a program to solve a problem of size n Time Space Define order of growth Visualizing resources utilization using our model of evaluation Relating

More information

Short Introduction to R

Short Introduction to R Short Introduction to R Paulino Pérez 1 José Crossa 2 1 ColPos-México 2 CIMMyT-México June, 2015. CIMMYT, México-SAGPDB Short Introduction to R 1/51 Contents 1 Introduction 2 Simple objects 3 User defined

More information

SF1901 Probability Theory and Statistics: Autumn 2016 Lab 0 for TCOMK

SF1901 Probability Theory and Statistics: Autumn 2016 Lab 0 for TCOMK Mathematical Statistics SF1901 Probability Theory and Statistics: Autumn 2016 Lab 0 for TCOMK 1 Preparation This computer exercise is a bit different from the other two, and has some overlap with computer

More information

Matrix Inverse 2 ( 2) 1 = 2 1 2

Matrix Inverse 2 ( 2) 1 = 2 1 2 Name: Matrix Inverse For Scalars, we have what is called a multiplicative identity. This means that if we have a scalar number, call it r, then r multiplied by the multiplicative identity equals r. Without

More information

Introduction to R Benedikt Brors Dept. Intelligent Bioinformatics Systems German Cancer Research Center

Introduction to R Benedikt Brors Dept. Intelligent Bioinformatics Systems German Cancer Research Center Introduction to R Benedikt Brors Dept. Intelligent Bioinformatics Systems German Cancer Research Center What is R? R is a statistical computing environment with graphics capabilites It is fully scriptable

More information

programming R: Functions and Methods

programming R: Functions and Methods programming R: Functions and Methods Adrian Waddell University of Waterloo Departement of Statistics and Actuarial Science September 8, 2010 About these Slides These slides were written on behalf of the

More information

Lambda Calculus see notes on Lambda Calculus

Lambda Calculus see notes on Lambda Calculus Lambda Calculus see notes on Lambda Calculus Shakil M. Khan adapted from Gunnar Gotshalks recap so far: Lisp data structures basic Lisp programming bound/free variables, scope of variables Lisp symbols,

More information

MATLAB Tutorial Matrices & Vectors MATRICES AND VECTORS

MATLAB Tutorial Matrices & Vectors MATRICES AND VECTORS MATRICES AND VECTORS A matrix (m x n) with m rows and n columns, a column vector (m x 1) with m rows and 1 column, and a row vector (1 x m) with 1 row and m columns all can be used in MATLAB. Matrices

More information