-1

I have a function which takes multiple inputs. The prototype is as follows:

func = function(x,y,z)

I have to maximise the function with respect to z. x and y are needed to run the function. Can I use optim or optimise for this? If yes, how?

Edit 1: Here is an example.

func = function(x,y,z)
{
  L=x^2*z+y*z;
  return (L);
}

Now, I want to find the maximum value of func(3,2,z) where z \in [-1,1]. Can I use optim/optimise here?

Harshvardhan
  • 479
  • 1
  • 3
  • 12
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Both the functions you list have examples on their help pages. Maybe start by looking there. – MrFlick Mar 13 '19 at 17:59
  • Okay, added an example. Can you have a look at it? – Harshvardhan Mar 13 '19 at 18:15

1 Answers1

1

Since you are optimizing over a single variable, you can just use optimize. For example

optimize(function(z) func(3,2,z), c(-1,1), maximum = TRUE)

Here we just create an anonymous function that locks in the values for x and y so it's just a function of z.

MrFlick
  • 195,160
  • 17
  • 277
  • 295