I would like to know if there is any function that will give a local maxima for matrix on a plane?
I found one solution from
Given a 2D numeric "height map" matrix in R, how can I find all local maxima?
but it seems that there are some mistakes where for this line
localmax <- focal(r, fun = f, pad=TRUE, padValue=NA)
Error in focal(r, fun = f, pad = TRUE, padValue = NA) :
argument "w" is missing
Not sure on how to contact the person who gave the solution, so I just post it here
Regards
Aftar
Personally I'd dump your matrix into imageJ to do this.
As another option, you might port this Matlab code http://www.mathworks.com/matlabcentral/fileexchange/37388-fast-2d-peak-finder . That module does some smoothing to improve the chance of finding "real" peaks in an image. IMHO local maxima only have meaning if the surface is smooth in the mathematical sense, i.e. everywhere differentiable.
Related
How do I plot decision boundary from weight vector?
My original data is 2-dimensional but non-linearly separable so I used a polynomial transformation of order 2 and therefore I ended up with a 6-dimensional weight vector.
Here's the code I used to generate my data:
polar2cart <- function(theta,R,x,y){
x = x+cos(theta) * R
y = y+sin(theta) * R
c=matrix(x,ncol=1000)
c=rbind(c,y)
}
cart2polar <- function(x, y)
{
r <- sqrt(x^2 + y^2)
t <- atan(y/x)
c(r,t)
}
R=5
eps=5
sep=-5
c1<-polar2cart(pi*runif(1000,0,1),runif(1000,0,eps)+R,0,0)
c2<-polar2cart(-pi*runif(1000,0,1),runif(1000,0,eps)+R,R+eps/2,-sep)
data <- data.frame("x" = append(c1[1,], c2[1,]), "y" = append(c1[2,], c2[2,]))
labels <- append(rep(1,1000), rep(-1, 1000))
and here's how it is displayed (using ggplot2):
Thank you in advance.
EDIT: I'm sorry if I didn't provide enough information about the weight vector. The algorithm I'm using is pocket which is a variation of perceptron, which means that the output weight vector is the perpendicular vector that determines the hyper-plane in the feature space plus the bias . Therefore, the hyper-plane equation is , where are the variables. Now, since I used a polynomial transformation of order 2 to go from a 2-dimensional space to a 5-dimensional space, my variables are : and thus the equation for my decision boundary is:
So basically, my question is how do I go about drawing my decision boundary given
PS: I've found a solution while waiting, it might not be the best approach but, it gives the expected results. I'll share it as soon as I finish my project if anyone is interested. Meanwhile, I'd love to hear a better alternative.
I have been running two unmarked planar point pattern data sets through a series of spatstat functions. Now I would like to use the Kcross.inhom function to describe interaction between the two, but Kcross only works with marked data, so I have combined all x-y data into one csv file and added a column that distinguishes the two. I have established the following point pattern object, but do not understand how to edit the subsequent example of Kcross for my purposes. Or, perhaps there is a better way? Thanks for your help!
# read in data & create ppp
collisionspotholes<-read.csv("cpmulti.csv")
cp<-ppp(collisionspotholes[,3],collisionspotholes[,4],c(40.50390735,40.91115166),c(-74.25262139,-73.7078596))
# synthetic example
pp <- runifpoispp(50)
pp <- pp %mark% factor(sample(0:1, npoints(pp), replace=TRUE))
K <- Kcross(pp, "0", "1")
K <- Kcross(pp, 0, 1) # equivalent
I am not really clear as to what the problem is that you are having. You seem to me to "be there" essentially. However let me, for completeness, spell out the procedure that you should follow:
Let X and Y be your two point patterns (observed, presumably, in the same window).
Put these together into a single pattern:
XY <- superimpose(X=X,Y=Y)
Note that there is no need to dick around with your csv files; it is much more efficient to use the facilities provided by spatstat.
The foregoing syntax produces a multitype point pattern with marks being a factor with levels "X" and "Y". (If you want the levels to be denoted by other symbols you can easily arrange this.)
Then just calculate the inhomogeneous Kcross function:
Ki <- Kcross.inhom(XY,"X","Y")
That is all that there is to it.
Note that the foregoing uses the default method of estimating the intensities of the two patterns, explicitly leave-one-out kernel smoothing with bandwidth chosen by bw.diggle(). There may be better ways of estimating the intensities, perhaps by fitting a parametric model. This depends on the nature of the information available to you.
Interpreting the output of Kcross.inhom() is, IMHO, subtle and difficult.
Be cautious in any conclusions that you draw.
Rolf Turner's answer is correct. However, you say that
I have combined all x-y data into one csv file and added a column that distinguishes the two.
OK, suppose the data frame is called df and it has columns named x and y giving the spatial coordinates and h which is a character vector identifying whether the corresponding point is a pothole (h="p") or a collision (h="c"). Then you could do
X <- ppp(df$x, df$y, xlim, ylim, marks=factor(df$h))
where xlim, ylim are the limits for the spatial coordinates. Or more elegantly
X <- with(df, ppp(x, y, xlim, ylim, marks=factor(h))
Note the use of factor to ensure that the marks are categorical values. Then type
X
to check that you've got a 'multitype point pattern'.
Then you can do, e.g.
K <- Kcross(X)
Ki <- Kcross.inhom(X)
Please read the help files for Kcross, Kcross.inhom for advice about how to use these functions and how to interpret the results.
Incidentally, please do not send the same question to multiple forums at the same time. That is difficult for those who have to answer.
Sorry this might be basic but I am a newbie. I will be making lots of curves so some advice will be useful for me.
I have a function which I want to plot:
f <- function(x) sum(4*sin(x*seq(1,21,2))/(pi*seq(1,21,2)))
using
curve(f, -pi, pi, n=100)
Unfortunately ,this does not work for me. Please advise.
Thanks
You function isn't vectorized. At the moment it will only take a single scalar input and output a single return value. curve expects that it should be able to feed in a vector of the x values it wants to plot for and should receive a vector of response values. The easiest solution is to just use Vectorize to automatically convert your function into one that can take vector inputs.
f2 <- Vectorize(f)
curve(f2, -pi, pi, n = 100)
However, you might just want to write a vectorized version of the function directly.
Is there a function for solving transcendental equations in R?
For example, I want to solve the following equation
x = 1/tan(x)
Any suggestions? I know the solution has multiple roots so I also want to be able to recover all the answers for a given interval
I would plot the function curve and look at it to see what it looks like:
R > y = function(x) { x - 1/tan(x) }
R > curve(y, xlim = c(-10, 10))
R > abline(h = 0, color = 'red')
Then I saw there is a root between 0 and 3, I would use uniroot to get the root I want:
R > uniroot(y, interval = c(0, 3))
$root
[1] 0.8603
$f.root
[1] 6.612e-06
$iter
[1] 7
$estim.prec
[1] 6.104e-05
You can use uniroot to find roots of any 1D equations within a given range. However, getting multiple roots seems like a very hard problem in general (e.g. see the relevant chapter of Numerical Recipes for some background: chapter 9 at http://apps.nrbook.com/c/index.html ). Which root is found when there are multiple roots is hard to predict. If you know enough about the problem to subdivide the space into subregions with zero or one roots, or if you're willing to divide it into lots of regions and hope that you found all the roots, you can do it. Otherwise I look forward to other peoples' solutions ...
In this particular case, as shown by #liuminzhao's solution, there's (at most? exactly?) one solution between n*pi and (n+1)*pi
y = function(x) x-1/tan(x)
curve(y,xlim=c(-10,10),n=501,ylim=c(-5,5))
abline(v=(-3:3)*pi,col="gray")
abline(h=0,col=2)
This is a bit of a hack, but it will find roots of your equation (provided they are not too close to a multiple of pi: you can reduce eps if you like ...). However, if you want to solve a different multi-root transcendental equation you might need another (specialized) strategy ...
f <- function(n,eps=1e-6) uniroot(y,c(n*pi+eps,(n+1)*pi-eps))$root
sapply(0:3,f)
## [1] 0.8603337 3.4256204 6.4372755 9.5293334
I'm wondering if it is possible to caclulate the area within a contour in R.
For example, the area of the contour that results from:
sw<-loess(m~l+d)
mypredict<-predict(sw, fitdata) # Where fitdata is a data.frame of an x and y matrix
contour(x=seq(from=-2, to=2, length=30), y=seq(from=0, to=5, length=30), z=mypredict)
Sorry, I know this code might be convoluted. If it's too tough to read. Any example where you can show me how to calculate the area of a simply generated contour would be helpful.
Thanks for any help.
I'm going to assume you are working with an object returned by contourLines. (An unnamed list with x and y components at each level.) I was expecting to find this in an easy to access location but instead found a pdf file that provided an algorithm which I vaguely remember seeing http://finzi.psych.upenn.edu/R/library/PBSmapping/doc/PBSmapping-UG.pdf (See pdf page 19, labeled "-11-") (Added note: The Wikipedia article on "polygon" cites this discussion of the Surveyors' Formula: http://www.maa.org/pubs/Calc_articles/ma063.pdf , which justifies my use of abs().)
Building an example:
x <- 10*1:nrow(volcano)
y <- 10*1:ncol(volcano)
contour(x, y, volcano);
clines <- contourLines(x, y, volcano)
x <- clines[[9]][["x"]]
y <- clines[[9]][["y"]]
level <- clines[[9]][["level"]]
level
#[1] 130
The area at level == 130 (chosen because there are not two 130 levels and it doesn't meet any of the plot boundaries) is then:
A = 0.5* abs( sum( x[1:(length(x)-1)]*y[2:length(x)] - y[1:(length(x)-1)]*x[2:length(x)] ) )
A
#[1] 233542.1
Thanks to #DWin for reproducible example, and to the authors of sos (my favourite R package!) and splancs ...
library(sos)
findFn("area polygon compute")
library(splancs)
with(clines[[9]],areapl(cbind(x,y)))
Gets the same answer as #DWin, which is comforting. (Presumably it's the same algorithm, but implemented within a Fortran routine in the splancs package ...)