# Getting two indexes for which maximum is reached

It’s not clear why you are passing a vector to this function then appending stuff to the end of it. I’m guessing you want `vec` to be empty.

A simple solution would be a modification like this:

``````choose_coef <- function() {
t <- seq(from = 1, to = 2, by = 0.5)
vec <- numeric()
for (i in 1:length(t)){
for (j in 1:length(t)){
vec <- append(vec, setNames(i/2 - j/2, paste0("i=", i, ";j=", j)))
}
}
names(which.max(vec))
}
``````

Which produces:

``````choose_coef()
#>  "i=3;j=1"
``````

Alternatively, the following function is self-describing, in that when run it outputs an explanation of how it works:

``````choose_coef <- function() {
t <- seq(from = 1, to = 2, by = 0.5)
vec <- numeric()
for (i in 1:length(t)){
for (j in 1:length(t)){
vec <- append(vec, i/2 - j/2)
}
}
cat("The maximum value was", max(vec), "which occurred at position",
which.max(vec), "\nSince there were", length(t),
"iterations of j for each of the", length(t),
"iterations of i,\nwe know that the maximum occurred on:\ni =",
(which.max(vec) - 1) %/% length(t) + 1, "and j =",
(which.max(vec) - 1) %% length(t) + 1)
}
``````

So we just do:

``````choose_coef()
#> The maximum value was 1 which occurred at position 7
#> Since there were 3 iterations of j for each of the 3 iterations of i,
#> we know that the maximum occurred on:
#> i = 3 and j = 1
``````

CLICK HERE to find out more related problems solutions.

Scroll to Top