# Stochastic Calculus, Courant Institute, NYU, Fall 2012 # Getting started with R, assignment 1a, an array and plot demo # (your name and email here) # Calculate and plot two curves, a linear curve and a cubic. # Compute and plot their intersection points. xMin = -2 # Coding style: short comments after a line of code xMax = 2 # Coding style: make things line up for clarity L = xMax - xMin # L = length of the interval nx = 50 # nx = number of points on x axis cp = array(1:nx) # creates a 1D array cp = (1, 2, ..., nx) lp = rep(0, nx) # creates a 1D array "replicating" nx zeros ... xp = rep(0, nx) # ... get xp = (0, 0, ..., 0) s = 2. # slope of a line to be plotted dx = L/(nx-1) # distance between nx uniformly spaced points # One way to do a loop x = xMin # start at the left end of the interval for (i in (1:nx)){ # Do the stuff in {...} for each i = 1, 2, ..., nx cp[i] = x*x*x - x # cp is a cubic xp[i] = x # save the x values, for plotting x = x + dx # increment x to the next point } # end of the loop # Another way to do the loop for (i in (1:nx)){ # same loop control statement x = xMin + (i-1)* dx # re-calculate the x value lp[i] = s*x # lp is linear with slope s } # end of the loop # Find three intersection points, (x1,y1), (x2,y2), (x3,y3) x1 = - sqrt(s+1) # a solution of x^3 - x = sx y1 = s*x1 # use the simpler formula for the y value x2 = 0 y2 = 0 x3 = - x1 y3 = x3*x3*x3 - x3 # the other formula should work too ix = c( x1, x2, x3) # c is for "concatenate". It makes an ... iy = c( y1, y2, y3) # ... array of the elements listed. # Plotting. Do this professionally. title = "Intersecting curves" # What's in quotes is a "string" of text ylabel = "a linear and a cubic function" xlabel = sprintf('x runs from %6.2f to %6.2f', # put values of variables.. xMin, xMax) # .. into a string. PlotInfo = sprintf('slope = %6.2f, nx = %4d points, dx = %6.2f', s, nx, dx) yMinMax = c( cp[1], cp[nx] ) # This two element list is the min and max of y # Draw the plots in a terminal window, in two steps: # If you need to open a terminal window, uncomment one of these # quartz() # for a mac. Uncomment this out if you are using a mac # x11(), # for linux. Uncomment this if using linux # windows() # for windows (Microsoft). Uncomment this if using windows. source('IntersectingCurvesPlot.R') # Plot commands are in a separate file # Draw the plots in a pdf file, in three steps: # Step 1: open a .pdf file in the desired directory, and desired name setwd("/Users/jg/desktop/notes/StochCalc2013/codes") # set the directory pdf( "Assignment1a.pdf") # open and name the plot file # Step 2: call the same R commands that do the same plotting source('IntersectingCurvesPlot.R') # Step 3: turn off the device you just turned on dev.off( which = dev.cur() ) # This closes the current "device", which ... # ... is the .pdf file. Otherwise the file .. # ... is not saved (or something).