STATISTICS 579 R Tutorial : Programming in R
|
|
- Reynold Simon
- 5 years ago
- Views:
Transcription
1 Fall Conditional computation in R: STATISTICS 579 R Tutorial : Programming in R The basic control structure available in R for conditional computation is of the form if (cond) expr-1 else expr-2 where cond is an expression that evaluates to a logical value, expr-1 is an R expression that will be executed if the value of cond is TRUE; expr-2, is an R expression that will be executed if the value of cond is FALSE. Both expr-1 and expr-2 may be either simple R expressions or compound R expressions. A compound R expression consists of a group of simple R expressions enclosed in braces. Note that several R expressions may be entered on the same line as long as they are separated by semi-colons. Some examples are: > a=25;b=50 > if(a>b)c=a else c=b > c [1] 50 > gpa=3.5; sat=560 > if (gpa<3 sat<600){ + category="b" + score=gpa+.007*sat } else { + category="a" + score=gpa+.006*sat } > category [1] "B" > score [1] 7.42 Note carefully that if there is a newline just before the else clause, the if statement is taken to be complete, because the if statement without an else part, is a valid R statement. Note also that the operators && and are used to combine logical comparisons to make compound logical expressions. As noted before, the operators & and must be used to combine logical vectors. The functions all() and any() are also useful for making compound logical expressions by combining the components of their arguments using the && and the operators, respectively. > h [1] > h>10 [1] TRUE TRUE FALSE FALSE > h[1]>10&&h[2]>10&&h[3]>10&&h[4]>10 [1] FALSE > all(h>10) [1] FALSE > h[1]>10 h[2]>10 h[3]>10 h[4]>10 [1] TRUE > any(h>10) [1] TRUE 1
2 These two functions can be used on the results of more complex logical expressions: > a=rnorm(100,5,2) > any(a>9.5) [1] TRUE > all(a>.5) [1] FALSE > any(a<.5 a>9.5) [1] TRUE > a[a<.5 a>9.5] [1] > (1:100)[a<.5 a>9.5] [1] If the logical expression cond results in a vector of logical values, the ifelse() function is better suited for conditional evaluation. It is of the form ifelse(cond, expr-1, expr-2) and returns a value of the same shape as expr-1, containing elements from expr-1 or expr-2 depending on whether the corresponding elements of cond are TRUE or FALSE, respectively. > x=6:-4 > x [1] > ifelse(x>0,x,-x) [1] > ifelse(x>0,x,na) [1] NA NA NA NA NA > ifelse(x>0,sqrt(x),-sqrt(-x)) [1] [8] Warning messages: 1: NaNs produced in: sqrt(x) 2: NaNs produced in: sqrt(-x) 2. Looping in R: There are three kinds of looping constructs in R: the for loop, the while loop, and my favorite, the repeat loop. Three purposes that a loop is used in computation are: for repeating the same transformation (or computation) on every element of a data structure, say, an array or a matrix, for forming sums, such as we saw in the case of computational formulas for the sample variance, or summation of series expansions, and for implementing iterative methods. It is possible in R to avoid using loops in the first two instances because of the vectorizing capability of R. Thus we can take square roots of every element in a vector object or find the sample variance of a data in a vector object, without using a loop. In order to understand iterative methods, some background knowledge in numerical computing is useful. This topic will be covered in a later class where the use of the above looping constructs to program iterative methods will be discussed. 2
3 (a) for loops This type of loop construct is suitable when the sequence of values of a variable through which a loop is repeated, is known in advance. The general form of the statement is for(name in seq) expr where seq is a sequence values usually in a vector or a list, name is a name of an object usually a scalar, and expr is a simple or compound R expression. Each value of seq is assigned to the name in turn and the expression is evaluated. Thus the expression is evaluated repeatedly for different values of name, whether or not its value is used in the evaluation of the expression. The loop is terminated and control passed on to the next statement when the sequence of values is exhausted. Some simple examples are: > x=10:20 > x [1] > for(i in 1:11) x[i]=x[i]^2 > x [1] In the above example, the variable i is used for extracting successive elements of a vector using subscripting. As demonstrated below, the use of a loop is unnecessary in this example as the exponentiation operation is vectorized. > x=10:20 > x=x^2 > x [1] Similarly, a loop is unnecessary to calculate the difference of two vectors as the difference operator is vectorized. Note carefully in the following example that objects being created new, must be initialized before subscripts can be used to reference their elements in a for loop. In the example, diff1 is the new vector being formed element at a time: > a=rnorm(100) > a[1:10] [1] [7] > b=rnorm(100) > b[1:10] [1] [7] > diff1=rep(0,100) > for(i in 1:100) diff1[i]=a[i]-b[i] > diff1[1:10] [1] [7] Again, the difference is formed using vectorization, and in this case no initialization is necessary: > diff2=a-b > diff2[1:10] [1] [7]
4 As an example of the second type of computation itemized above, i.e., forming sums, consider the use of a for loop for the computation of sample variance using the twopass formula. Here loops are used for accumulating intermediate sums. > wtmean=0 > n=length(weight) > for( i in 1:n) wtmean=wtmean+weight[i] > wtmean=wtmean/n > wtvar=0 > for(i in 1:n) wtvar=wtvar+(weight[i]-wtmean)^2 > wtvar=wtvar/(n-1) > wtvar [1] > var(weight) [1] Recall that earlier we used the sum() function to perform the above computation. One may assume that for loops are necessary to accomplish many tasks involving selecting elements of matrices or arrays. While in many lower level languages this type of computation may require looping, in R these might be conveniently handled by subscripting methods described earlier. For example, two nested for loops are necessary for changing all negative values in a matrix to zero using looping: > mdata=c(1.2,3.5,4.7,1.8,-6.4,5.4,-1.9,2.7,3.4,-2.0,7.2,4.5) > m=matrix(mdata,3,4,byrow=t) > m [,1] [,2] [,3] [,4] [1,] [2,] [3,] > for(i in 1:dim(m)[1]) + for(j in 1:dim(m)[2]) + if(m[i,j]<0) m[i,j]=0 > m [,1] [,2] [,3] [,4] [1,] [2,] [3,] As seen earlier, the same result can be achieved in a single statement: > m=matrix(mdata,3,4,byrow=t) > m [,1] [,2] [,3] [,4] [1,] [2,] [3,] > m[m<0]=0 > m [,1] [,2] [,3] [,4] [1,] [2,] [3,]
5 A fancier use of subscripts to avoid looping is illustrated in the following example, where subscripts are used to shift the contents of a vector to the left by a position. The vector of standard normals is used again in this example: > a[1:10] [1] [7] > for(i in 1:100) a[i]=a[i+1] > a[1:10] [1] [7] > jj=1:100 > a[jj]=a[jj+1] > a[1:10] [1] [8] > a[95:100] [1] NA NA Below is an example where two nested for loops are used for computing the treatment totals of the weights for each of the levels of the factor feed. Note that the sequence in the second for loop here is a vector of character values. > chickwts > attach(chickwts) > levels(feed) [1] "casein" "horsebean" "linseed" "meatmeal" "soybean" "sunflower" > tots=rep(0,6) > names(tots)=levels(feed) > tots casein horsebean linseed meatmeal soybean sunflower > for(i in 1:71){ + for(diet in levels(feed)) + if(feed[i]==diet) tots[diet]=tots[diet]+weight[i] + } > tots casein horsebean linseed meatmeal soybean sunflower (b) while loops This kind of looping structure is suitable when the number of times the computations contained within the loop is repeated is not known in advance, and the termination of the loop is dependent on some other criteria. The general form of the while loop is: while(cond) expr The simple or compound R expression, expr, is repeatedly executed until the logical expression cond evaluates to a FALSE value. Then the loop is exited and control transfers to the next statement. The value of the cond logical expression must necessarily depend on computations carried out in expr. Below, an example previously used to illustrate the for loop, is redone using a while loop. Note that the loop counter j is incremented inside the loop. 5
6 > a=rnorm(100) > b=rnorm(100) > diff3=null > j=0 > while(j<100){ + j=j+1 + diff3[j]=a[j]-b[j] + } > diff3[1:10] [1] [7] In practice, a while loop is preferred when the cond expression is used for other purposes than just counting. It can be used, for example, to determine if a terminating condition such as that the error in a computed answer has decreased to be smaller than a prespecified tolerance level and therefore is acceptable. For example, the following loop accumulates a sum to compute exp(5) using the power series 1 + x + x2 2! + expansion: > i=0 > term=1 > sum=1 > x=5 > while(term>.0001){ + i=i+1 + term=x^i/factorial(i) + sum=sum+term + } > sum [1] > exp(5) [1] The loop is terminated when the value of the next term to be added to the series is less than or equal to Note that this loop will not work for negative vales of x.m Of course, if we knew that we need 21 terms in the series to achieve this accuracy of the result, we could have used the expression: > 1+sum(5^(1:20)/factorial(1:20)) [1] (c) repeat loops The repeat loop is similar to the while loop except that the condition for termination is tested inside the loop. This allows for more than a single condition to be checked and for these conditions to occur at different places in the loop. The general form of the repeat loop is: repeat expr where the expr is usually an R compound expression. The expression is evaluated repeatedly so that at least one break statement must be in the loop. The loop will be exited only when a given condition is satisfied. A break statement is of the form if(cond) break and any number of these statements may appear at different places in the loop with different cond logical expressions. 6
7 For example the while loop in the previous example may be rewritten as follows: > i=0 > sum=1 > x=5 > repeat{ + i=i+1 + term=x^i/factorial(i) + if(term<=.0001) break + sum=sum+term + } > sum [1] Thus there is not too much of a difference between a repeat and a while loop, unless there are more than a single test and exit points. Otherwise, the choice depends on how the user wants to organize the computations within the loop, and when the condition for exiting the loop is checked. 3. Creating and using R scripts If a sequence of R commands are to be executed a second time, it is cumbersome to enter them again one-command-at-a-time at the R prompt, especially if some commands are continued into several lines, as in the above example. The sequence can be editted into a script file and then sourced into R to be executed. The script file may also be re-editted to modify the code if necessary. These pieces of R code need not be R functions nor do they need not be made into R functions. The user selects the drop down menu option File New script to open a window for doing text editing. Once the set of R commands is entered as text, save the file in your current working directory (or another selected directory) using the menu option File Save as... while the editor window is selected. For example, enter the sequence of R commands i=0 sum=1 x=5 repeat{ i=i+1 term=x^i/factorial(i) sum=sum+term if(term<=.0001)break cat(" i = ",i, " Term = ", term, " Sum = ",sum,fill=t) } cat (" Final Value=", sum, fill=t) in the editor window and save it as log.r). In practice, a file name with a file type of.r, such as log.r), needs to be chosen to save scripts. R code saved in script file may be executed using the menu option File Source R code... and selecting the appropriate script file to run from the current working directory (or another selected directory). Any previously created scripts may be retrieved for further editing using the menu option File Open script... and selecting the appropriate file from the current working directory (or another selected directory). The editor window opened by default is the one set in the R function options(). The internal R editor is set-up as the default editor but the user may change it to something else: e.g. options(editor="notepad") 7
8 4. Evaluating Polynomials We used the infinite series expansion for exp(x) to compute exp(5.0) accurately. A bound for the truncation error of the series was used to determine the number of terms necessary to be summed to compute exp(5.0) to a required accuracy. If the same series is used to compute exp( 9.1), for example, although a certain number of terms of the series should be sufficient to obtain a required accuracy theoretically, the computed value may not have enough correct significant digits. For negative values of x, the alternate terms in the series are of opposite signs and consequently loss of significant digits will occur as the cumulative sum is formed. Loss of significant digits takes place when two numbers of similar magnitudes of the same sign are subtracted. One way to avoid this when alternating terms of a series are of opposite signs, is to form the differences before summing them up. For example in summing the series a 0 a 1 x + a 2 x 2 a 3 x 3 + form the successive differences a 0 a 1 x, a 2 x 2 a 3 x 3 first. A better way to compute exp( x) is to use the relation exp( x) = 1/ exp(x). In practice infinite series are hardly used for the purpose of calculating functions. Instead, various function approximation methods are utilized to derive finite series approximations. A polynomial f(x) of degree n is a function of the form f(x) = a 0 + a 1 x + a 2 x a n x n (1) This form, called the power form, is the standard method of representing polynomial functions for mathematical purposes. However, if polynomials are to be evaluated in numerical computations, using other representations of f(x), one of which is discussed below, often leads to increased accuracy. The reason for this is that these representations are morenumerically stable than the power form. One such representation, often called Horner s rule, f(x) of (1) is re-expressed in the form Consider the evaluation of f(x) = a 0 + (a 1 + (a 2... (a n 1 + a n x)x...)x. (2) f(x) = 7 + 3x + 4x 2 9x 3 + 5x 4 + 2x 5. An expression for evaluating f(x) using Horner s rule is (3.0 + (4.0 + ( ( x) x) x) x) x which requires only 5 multiplications, which is 10 multiplications less than evaluating f(x) using the expression x x 2 9.0x 3 + where x 2 is counted as a multiplication. This representation can be coded in the following form in R: sum= a[n] for (i in n-1:1){ sum=sum*x+a[i] } cat(" Series sum = ",sum,fill=t) 8
9 where a is a vector containing the coefficients a 1, a 2,..., a n A finite series approximation for cos x is given by cos x = a 0 + a 2 x 2 + a 4 x 4 + a 6 x 6 + a 8 x 6 + a 10 x 10 + ɛ(x) where 0 x π/2 and (ɛ(x) , and the constants are a 2 = , a 4 = , a 6 = , a 8 = , a 10 = The following script in R uses this approximation to compute cos (1.234) x=1.234 a=c(1, , , , , ) sum=a[6] for (i in 5:1){ sum=sum*x^2+a[i] } cat(" x=", x, " approx cosine = ", round(sum,8), " true value = ", round(cos(x),8),fill=t) Executing this code gave the result x= approx cosine = true value =
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 informationChapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++
Repetition Contents 1 Repetition 1.1 Introduction 1.2 Three Types of Program Control Chapter 5 Introduction 1.3 Two Types of Repetition 1.4 Three Structures for Looping in C++ 1.5 The while Control Structure
More informationThere are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.
Introduction In the programs that we have dealt with so far, all statements inside the main function were executed in sequence as they appeared, one after the other. This type of sequencing is adequate
More informationRepetition Structures Chapter 9
Sum of the terms Repetition Structures Chapter 9 1 Value of the Alternating Harmonic Series 0.9 0.8 0.7 0.6 0.5 10 0 10 1 10 2 10 3 Number of terms Objectives After studying this chapter you should be
More informationRepetition Structures
Repetition Structures Chapter 5 Fall 2016, CSUS Introduction to Repetition Structures Chapter 5.1 1 Introduction to Repetition Structures A repetition structure causes a statement or set of statements
More informationChapter 7: Programming in MATLAB
The Islamic University of Gaza Faculty of Engineering Civil Engineering Department Computer Programming (ECIV 2302) Chapter 7: Programming in MATLAB 1 7.1 Relational and Logical Operators == Equal to ~=
More informationMATLAB Lesson I. Chiara Lelli. October 2, Politecnico di Milano
MATLAB Lesson I Chiara Lelli Politecnico di Milano October 2, 2012 MATLAB MATLAB (MATrix LABoratory) is an interactive software system for: scientific computing statistical analysis vector and matrix computations
More informationOutline. CSE 1570 Interacting with MATLAB. Outline. Starting MATLAB. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.
CSE 10 Interacting with MATLAB Instructor: Aijun An Department of Computer Science and Engineering York University aan@cse.yorku.ca Outline Starting MATLAB MATLAB Windows Using the Command Window Some
More informationCOMP 208 Computers in Engineering
COMP 208 Computers in Engineering Lecture 14 Jun Wang School of Computer Science McGill University Fall 2007 COMP 208 - Lecture 14 1 Review: basics of C C is case sensitive 2 types of comments: /* */,
More informationCondition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.
Repetition Structures Introduction to Repetition Structures Chapter 5 Spring 2016, CSUS Chapter 5.1 Introduction to Repetition Structures The Problems with Duplicate Code A repetition structure causes
More informationAN INTRODUCTION TO MATLAB
AN INTRODUCTION TO MATLAB 1 Introduction MATLAB is a powerful mathematical tool used for a number of engineering applications such as communication engineering, digital signal processing, control engineering,
More informationA QUICK INTRODUCTION TO MATLAB
A QUICK INTRODUCTION TO MATLAB Very brief intro to matlab Basic operations and a few illustrations This set is independent from rest of the class notes. Matlab will be covered in recitations and occasionally
More informationAn introduction to Scheme
An introduction to Scheme Introduction A powerful programming language is more than just a means for instructing a computer to perform tasks. The language also serves as a framework within which we organize
More informationMAT 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 informationA QUICK INTRODUCTION TO MATLAB. Intro to matlab getting started
A QUICK INTRODUCTION TO MATLAB Very brief intro to matlab Intro to matlab getting started Basic operations and a few illustrations This set is indepent from rest of the class notes. Matlab will be covered
More informationOUTLINES. 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 informationChapter 1: Number and Operations
Chapter 1: Number and Operations 1.1 Order of operations When simplifying algebraic expressions we use the following order: 1. Perform operations within a parenthesis. 2. Evaluate exponents. 3. Multiply
More informationOutline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.
CSE 170 Interacting with MATLAB Instructor: Aijun An Department of Computer Science and Engineering York University aan@cse.yorku.ca Outline Starting MATLAB MATLAB Windows Using the Command Window Some
More informationJME Language Reference Manual
JME Language Reference Manual 1 Introduction JME (pronounced jay+me) is a lightweight language that allows programmers to easily perform statistic computations on tabular data as part of data analysis.
More informationMatlab Introduction. Scalar Variables and Arithmetic Operators
Matlab Introduction Matlab is both a powerful computational environment and a programming language that easily handles matrix and complex arithmetic. It is a large software package that has many advanced
More informationDr Richard Greenaway
SCHOOL OF PHYSICS, ASTRONOMY & MATHEMATICS 4PAM1008 MATLAB 2 Basic MATLAB Operation Dr Richard Greenaway 2 Basic MATLAB Operation 2.1 Overview 2.1.1 The Command Line In this Workshop you will learn how
More informationC/C++ Programming for Engineers: Matlab Branches and Loops
C/C++ Programming for Engineers: Matlab Branches and Loops John T. Bell Department of Computer Science University of Illinois, Chicago Review What is the difference between a script and a function in Matlab?
More informationChapter 2: Functions and Control Structures
Chapter 2: Functions and Control Structures TRUE/FALSE 1. A function definition contains the lines of code that make up a function. T PTS: 1 REF: 75 2. Functions are placed within parentheses that follow
More informationWhat is MATLAB and howtostart it up?
MAT rix LABoratory What is MATLAB and howtostart it up? Object-oriented high-level interactive software package for scientific and engineering numerical computations Enables easy manipulation of matrix
More informationOutline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline (Cont d) MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An
CSE 170 Interacting with MATLAB Instructor: Aijun An Department of Computer Science and Engineering York University aan@cse.yorku.ca Outline Starting MATLAB MATLAB Windows Using the Command Window Some
More informationControl 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 informationConstraint-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 informationLECTURE 0: Introduction and Background
1 LECTURE 0: Introduction and Background September 10, 2012 1 Computational science The role of computational science has become increasingly significant during the last few decades. It has become the
More informationBC An Arbitrary Precision Desk-Calculator Language. Lorinda Cherry Robert Morris Bell Laboratories Murray Hill, New Jersey ABSTRACT
BC An Arbitrary Precision Desk-Calculator Language Lorinda Cherry Robert Morris Bell Laboratories Murray Hill, New Jersey 07974 ABSTRACT BC is a language and a compiler for doing arbitrary precision arithmetic
More informationChapter 1 Introduction to MATLAB
Chapter 1 Introduction to MATLAB 1.1 What is MATLAB? MATLAB = MATrix LABoratory, the language of technical computing, modeling and simulation, data analysis and processing, visualization and graphics,
More informationLECTURE 5 Control Structures Part 2
LECTURE 5 Control Structures Part 2 REPETITION STATEMENTS Repetition statements are called loops, and are used to repeat the same code multiple times in succession. The number of repetitions is based on
More informationComputers in Engineering COMP 208 Repetition and Storage Michael A. Hawker. Repetition. A Table of Values 9/20/2007
Computers in Engineering COMP 208 Repetition and Storage Michael A. Hawker Repetition To fully take advantage of the speed of a computer, we must be able to instruct it to do a lot of work The program
More informationIntroduction to Matlab. By: Dr. Maher O. EL-Ghossain
Introduction to Matlab By: Dr. Maher O. EL-Ghossain Outline: q What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators (Arithmetic, relational, logical ) Display Facilities Flow Control
More informationTable : IEEE Single Format ± a a 2 a 3 :::a 8 b b 2 b 3 :::b 23 If exponent bitstring a :::a 8 is Then numerical value represented is ( ) 2 = (
Floating Point Numbers in Java by Michael L. Overton Virtually all modern computers follow the IEEE 2 floating point standard in their representation of floating point numbers. The Java programming language
More informationIntroduction to MATLAB Practical 1
Introduction to MATLAB Practical 1 Daniel Carrera November 2016 1 Introduction I believe that the best way to learn Matlab is hands on, and I tried to design this practical that way. I assume no prior
More informationComputer Programming in MATLAB
Computer Programming in MATLAB Prof. Dr. İrfan KAYMAZ Atatürk University Engineering Faculty Department of Mechanical Engineering What is a computer??? Computer is a device that computes, especially a
More informationBasic stuff -- assignments, arithmetic and functions
Basic stuff -- assignments, arithmetic and functions Most of the time, you will be using Maple as a kind of super-calculator. It is possible to write programs in Maple -- we will do this very occasionally,
More informationBranches, Conditional Statements
Branches, Conditional Statements Branches, Conditional Statements A conditional statement lets you execute lines of code if some condition is met. There are 3 general forms in MATLAB: if if/else if/elseif/else
More informationMATLAB QUICK START TUTORIAL
MATLAB QUICK START TUTORIAL This tutorial is a brief introduction to MATLAB which is considered one of the most powerful languages of technical computing. In the following sections, the basic knowledge
More informationComputational Mathematics: Models, Methods and Analysis. Zhilin Li
Computational Mathematics: Models, Methods and Analysis Zhilin Li Chapter 1 Introduction Why is this course important (motivations)? What is the role of this class in the problem solving process using
More informationUniversity of Alberta
A Brief Introduction to MATLAB University of Alberta M.G. Lipsett 2008 MATLAB is an interactive program for numerical computation and data visualization, used extensively by engineers for analysis of systems.
More informationIntroduction to R. Stat Statistical Computing - Summer Dr. Junvie Pailden. July 5, Southern Illinois University Edwardsville
Introduction to R Stat 575 - Statistical Computing - Summer 2016 Dr. Junvie Pailden Southern Illinois University Edwardsville July 5, 2016 Why R R offers a powerful and appealing interactive environment
More informationREPETITION CONTROL STRUCTURE LOGO
CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE 1 Contents 1 Introduction 2 for loop 3 while loop 4 do while loop 2 Introduction It is used when a statement or a block of
More informationIntroduction to MATLAB
Introduction to MATLAB 1 Introduction to MATLAB A Tutorial for the Course Computational Intelligence http://www.igi.tugraz.at/lehre/ci Stefan Häusler Institute for Theoretical Computer Science Inffeldgasse
More informationIntroduction to MATLAB
Introduction to MATLAB Introduction MATLAB is an interactive package for numerical analysis, matrix computation, control system design, and linear system analysis and design available on most CAEN platforms
More informationIntroduction to MATLAB
Introduction to MATLAB The Desktop When you start MATLAB, the desktop appears, containing tools (graphical user interfaces) for managing files, variables, and applications associated with MATLAB. The following
More informationLecture Transcript While and Do While Statements in C++
Lecture Transcript While and Do While Statements in C++ Hello and welcome back. In this lecture we are going to look at the while and do...while iteration statements in C++. Here is a quick recap of some
More informationProblem Solving and 'C' Programming
Problem Solving and 'C' Programming Targeted at: Entry Level Trainees Session 05: Selection and Control Structures 2007, Cognizant Technology Solutions. All Rights Reserved. The information contained herein
More informationPHYS 210: Introduction to Computational Physics Octave/MATLAB Exercises 1
PHYS 210: Introduction to Computational Physics Octave/MATLAB Exercises 1 1. Problems from Gilat, Ch. 1.10 Open a terminal window, change to directory /octave, and using your text editor, create the file
More informationTheory of control structures
Theory of control structures Paper written by Bohm and Jacopini in 1966 proposed that all programs can be written using 3 types of control structures. Theory of control structures sequential structures
More informationProgramming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029
Programming Basics and Practice GEDB029 Decision Making, Branching and Looping Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029 Decision Making and Branching C language possesses such decision-making capabilities
More informationShort Version of Matlab Manual
Short Version of Matlab Manual This is an extract from the manual which was used in MA10126 in first year. Its purpose is to refamiliarise you with the matlab programming concepts. 1 Starting MATLAB 1.1.1.
More informationProject 1: Part 1. Project 1 will be to calculate orthogonal polynomials. It will have several parts. x = b± b 2 4ac., x 2 = b b 2 4ac.
Project 1: Part 1 Project 1 will be to calculate orthogonal polynomials. It will have several parts. Warmup: Solving quadratic equations The quadratic formula says that the solutions of ax 2 +bx+c = 0
More informationWeek 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.
Week 2 Branching & Looping Gaddis: Chapters 4 & 5 CS 5301 Spring 2018 Jill Seaman 1 Relational Operators l relational operators (result is bool): == Equal to (do not use =)!= Not equal to > Greater than
More informationBoolean Logic & Branching Lab Conditional Tests
I. Boolean (Logical) Operations Boolean Logic & Branching Lab Conditional Tests 1. Review of Binary logic Three basic logical operations are commonly used in binary logic: and, or, and not. Table 1 lists
More informationDecision Making in C
Decision Making in C Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed
More informationMATH 2650/ Intro to Scientific Computation - Fall Lab 1: Starting with MATLAB. Script Files
MATH 2650/3670 - Intro to Scientific Computation - Fall 2017 Lab 1: Starting with MATLAB. Script Files Content - Overview of Course Objectives - Use of MATLAB windows; the Command Window - Arithmetic operations
More informationMATLAB Project: Getting Started with MATLAB
Name Purpose: To learn to create matrices and use various MATLAB commands for reference later MATLAB functions used: [ ] : ; + - * ^, size, help, format, eye, zeros, ones, diag, rand, round, cos, sin,
More informationWhat 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 informationMATLAB: The Basics. Dmitry Adamskiy 9 November 2011
MATLAB: The Basics Dmitry Adamskiy adamskiy@cs.rhul.ac.uk 9 November 2011 1 Starting Up MATLAB Windows users: Start up MATLAB by double clicking on the MATLAB icon. Unix/Linux users: Start up by typing
More informationCS1100 Introduction to Programming
Decisions with Variables CS1100 Introduction to Programming Selection Statements Madhu Mutyam Department of Computer Science and Engineering Indian Institute of Technology Madras Course Material SD, SB,
More information2 Computation with Floating-Point Numbers
2 Computation with Floating-Point Numbers 2.1 Floating-Point Representation The notion of real numbers in mathematics is convenient for hand computations and formula manipulations. However, real numbers
More informationLoopy 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 information1.1 calculator viewing window find roots in your calculator 1.2 functions find domain and range (from a graph) may need to review interval notation
1.1 calculator viewing window find roots in your calculator 1.2 functions find domain and range (from a graph) may need to review interval notation functions vertical line test function notation evaluate
More informationThe Very Basics of the R Interpreter
Chapter 2 The Very Basics of the R Interpreter OK, the computer is fired up. We have R installed. It is time to get started. 1. Start R by double-clicking on the R desktop icon. 2. Alternatively, open
More informationRelational and Logical Statements
Relational and Logical Statements Relational Operators in MATLAB A operator B A and B can be: Variables or constants or expressions to compute Scalars or arrays Numeric or string Operators: > (greater
More informationReals 1. Floating-point numbers and their properties. Pitfalls of numeric computation. Horner's method. Bisection. Newton's method.
Reals 1 13 Reals Floating-point numbers and their properties. Pitfalls of numeric computation. Horner's method. Bisection. Newton's method. 13.1 Floating-point numbers Real numbers, those declared to be
More informationIntroduction to Matlab
Introduction to Matlab By:Mohammad Sadeghi *Dr. Sajid Gul Khawaja Slides has been used partially to prepare this presentation Outline: What is Matlab? Matlab Screen Basic functions Variables, matrix, indexing
More informationCS321 Introduction To Numerical Methods
CS3 Introduction To Numerical Methods Fuhua (Frank) Cheng Department of Computer Science University of Kentucky Lexington KY 456-46 - - Table of Contents Errors and Number Representations 3 Error Types
More informationLoops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017
Loops! Loops! Loops! Lecture 5 COP 3014 Fall 2017 September 25, 2017 Repetition Statements Repetition statements are called loops, and are used to repeat the same code mulitple times in succession. The
More informationMAT 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 information8. Control statements
8. Control statements A simple C++ statement is each of the individual instructions of a program, like the variable declarations and expressions seen in previous sections. They always end with a semicolon
More informationC++ Programming Lecture 1 Software Engineering Group
C++ Programming Lecture 1 Software Engineering Group Philipp D. Schubert Contents 1. More on data types 2. Expressions 3. Const & Constexpr 4. Statements 5. Control flow 6. Recap More on datatypes: build-in
More information5 The Control Structure Diagram (CSD)
5 The Control Structure Diagram (CSD) The Control Structure Diagram (CSD) is an algorithmic level diagram intended to improve the comprehensibility of source code by clearly depicting control constructs,
More information2 Computation with Floating-Point Numbers
2 Computation with Floating-Point Numbers 2.1 Floating-Point Representation The notion of real numbers in mathematics is convenient for hand computations and formula manipulations. However, real numbers
More informationTopics. Introduction to Repetition Structures Often have to write code that performs the same task multiple times. Controlled Loop
Topics C H A P T E R 4 Repetition Structures Introduction to Repetition Structures The for Loop: a Count- Sentinels Nested Loops Introduction to Repetition Structures Often have to write code that performs
More informationLAB 2: Linear Equations and Matrix Algebra. Preliminaries
Math 250C, Section C2 Hard copy submission Matlab # 2 1 Revised 07/13/2016 LAB 2: Linear Equations and Matrix Algebra In this lab you will use Matlab to study the following topics: Solving a system of
More informationBC An Arbitrary Precision Desk-Calculator Language
Lorinda Cherry Robert Morris ABSTRACT BC is a language and a compiler for doing arbitrary precision arithmetic on the PDP-11 under the UNIX time-sharing system. The output of the compiler is interpreted
More informationQueens College, CUNY, Department of Computer Science Numerical Methods CSCI 361 / 761 Spring 2018 Instructor: Dr. Sateesh Mane.
Queens College, CUNY, Department of Computer Science Numerical Methods CSCI 36 / 76 Spring 208 Instructor: Dr. Sateesh Mane c Sateesh R. Mane 208 Lecture February 25, 208 This is a collection of useful
More information6.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 informationChapter 4 Introduction to Control Statements
Introduction to Control Statements Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives 2 How do you use the increment and decrement operators? What are the standard math methods?
More informationPart V Appendices c Copyright, Todd Young and Martin Mohlenkamp, Department of Mathematics, Ohio University, 2017
Part V Appendices c Copyright, Todd Young and Martin Mohlenkamp, Department of Mathematics, Ohio University, 2017 Appendix A Glossary of Matlab Commands Mathematical Operations + Addition. Type help plus
More informationMath 56 Homework 1. Matthew Jin. April 3, e n 10+ne. = O(n 1 ) n > n 0, where n 0 = 0 be- 10+ne
Math 56 Homework 1 Matthew Jin April 3, 2014 1a) e n 10+ne is indeed equal to big O of n 1 e as n approaches infinity. Let n n 10+ne n C n 1 for some constant C. Then ne n 10+ne C n Observe that Choose
More informationIntroduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop
Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #16 Loops: Matrix Using Nested for Loop In this section, we will use the, for loop to code of the matrix problem.
More informationIntroduction to Engineering gii
25.108 Introduction to Engineering gii Dr. Jay Weitzen Lecture Notes I: Introduction to Matlab from Gilat Book MATLAB - Lecture # 1 Starting with MATLAB / Chapter 1 Topics Covered: 1. Introduction. 2.
More informationFundamentals of Programming Session 13
Fundamentals of Programming Session 13 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2014 These slides have been created using Deitel s slides Sharif University of Technology Outlines
More informationMathematical Experiments with Mathematica
Mathematical Experiments with Mathematica Instructor: Valentina Kiritchenko Classes: F 12:00-1:20 pm E-mail : vkiritchenko@yahoo.ca, vkiritch@hse.ru Office hours : Th 5:00-6:20 pm, F 3:30-5:00 pm 1. Syllabus
More informationMATLAB NOTES. Matlab designed for numerical computing. Strongly oriented towards use of arrays, one and two dimensional.
MATLAB NOTES Matlab designed for numerical computing. Strongly oriented towards use of arrays, one and two dimensional. Excellent graphics that are easy to use. Powerful interactive facilities; and programs
More informationCMAT Language - Language Reference Manual COMS 4115
CMAT Language - Language Reference Manual COMS 4115 Language Guru: Michael Berkowitz (meb2235) Project Manager: Frank Cabada (fc2452) System Architect: Marissa Ojeda (mgo2111) Tester: Daniel Rojas (dhr2119)
More informationAn interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s.
Using Monte Carlo to Estimate π using Buffon s Needle Problem An interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s. Here s the problem (in a simplified form). Suppose
More informationUniversity of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.
University of Technology Laser & Optoelectronics Engineering Department C++ Lab Sixth week Jump statements The break statement Using break we can leave a loop even if the condition for its end is not fulfilled
More informationFloating-point numbers. Phys 420/580 Lecture 6
Floating-point numbers Phys 420/580 Lecture 6 Random walk CA Activate a single cell at site i = 0 For all subsequent times steps, let the active site wander to i := i ± 1 with equal probability Random
More informationü 1.1 Getting Started
Chapter 1 Introduction Welcome to Mathematica! This tutorial manual is intended as a supplement to Rogawski's Calculus textbook and aimed at students looking to quickly learn Mathematica through examples.
More informationA 30 Minute Introduction to Octave ENGR Engineering Mathematics Tony Richardson
A 30 Minute Introduction to Octave ENGR 390 - Engineering Mathematics Tony Richardson Introduction This is a brief introduction to Octave. It covers several topics related to both the statistics and linear
More informationMAT 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 informationUnit 3 Decision making, Looping and Arrays
Unit 3 Decision making, Looping and Arrays Decision Making During programming, we have a number of situations where we may have to change the order of execution of statements based on certain conditions.
More informationMacro Programming Reference Guide. Copyright 2005 Scott Martinez
Macro Programming Reference Guide Copyright 2005 Scott Martinez Section 1. Section 2. Section 3. Section 4. Section 5. Section 6. Section 7. What is macro programming What are Variables What are Expressions
More informationIntroduction to Matlab. By: Hossein Hamooni Fall 2014
Introduction to Matlab By: Hossein Hamooni Fall 2014 Why Matlab? Data analytics task Large data processing Multi-platform, Multi Format data importing Graphing Modeling Lots of built-in functions for rapid
More informationMATLAB Project: Getting Started with MATLAB
Name Purpose: To learn to create matrices and use various MATLAB commands for reference later MATLAB built-in functions used: [ ] : ; + - * ^, size, help, format, eye, zeros, ones, diag, rand, round, cos,
More informationARRAY VARIABLES (ROW VECTORS)
11 ARRAY VARIABLES (ROW VECTORS) % Variables in addition to being singular valued can be set up as AN ARRAY of numbers. If we have an array variable as a row of numbers we call it a ROW VECTOR. You can
More information