I got a nested loop:
SA_range <- seq(0.01, 89.99, by = 0.01)
SR_value <- c(0.182, 0.307, 0.408, 0.603, 0.720, 0.823, 0.998)
library(tidyverse)
library(pracma)
for (i in SR_value) {
for (j in SA_range) {
if (near((cot(j*(pi/180))*log(tan(j*(pi/180)) sec(j*(pi/180)))), # my formula
i,
tol = 0.0002)) {
print(c(i, j))
}
}
}
What I'm trying to do here is substituting every number from SA_range
into the formula to see if the formula output matches values in SR_value
, and if the output does match SR_value
at the given accuracy (0.0002
), then print SR_value
and corresponding value(s) in SA_range
.
The loop works fine but the problem to me is storing the results (currently I can only print them). The challnege is that my actual SR_value
has a lot more values than this example and sometime mutiple values in SA_range
can be found by the loop. For example, when SR = 0.182, there is only one SA value matches the formula output, but when SR = 0.998, there are 63 SA values match the output! (code not shown here to save space)
So basically, assume the length of results of this loop is unknown, how can I store all the results?
(This is a case of solving an equation by iteration, so any other efficient methods are also welcome!)
CodePudding user response:
You can try -
SA_range <- seq(0.01, 89.99, by = 0.01)
SR_value <- c(0.182, 0.307, 0.408, 0.603, 0.720, 0.823, 0.998)
library(tidyverse)
library(pracma)
results <- list()
k <- 0
for (i in SR_value) {
for (j in SA_range) {
value <- (cot(j*(pi/180))*log(tan(j*(pi/180)) sec(j*(pi/180))))
if (near(value, i, tol = 0.0002)) {
k <- k 1
results[[k]] <- c(i, j)
}
}
}
results
#[[1]]
#[1] 0.182 87.190
#[[2]]
#[1] 0.307 84.080
#[[3]]
#[1] 0.307 84.090
#[[4]]
#[1] 0.408 80.800
#[[5]]
#[1] 0.408 80.810
#...
CodePudding user response:
Solution for your usecase:
results <- list()
for (i in SR_value) {
SAresults <- numeric()
for (j in SA_range) {
if (near((cot(j*(pi/180))*log(tan(j*(pi/180)) sec(j*(pi/180)))), # my formula
i,
tol = 0.0002)) {
SAresults <- c(SAresults, j)
}
results[[as.character(i)]] <- SAresults
}
}
A minimal reproducible example of the suggested solution:
SA_range <- seq(0.01, 89.99, by = 0.01)
SR_value <- c(0.182, 0.307, 0.408, 0.603, 0.720, 0.823, 0.998)
results <- list()
for (i in SR_value) {
SAresults <- numeric()
for (j in SA_range) {
if (j < 0.03) {
SAresults <- c(SAresults, j)
}
results[[as.character(i)]] <- SAresults
}
}
results
Returns:
$`0.182`
[1] 0.01 0.02
$`0.307`
[1] 0.01 0.02
$`0.408`
[1] 0.01 0.02
$`0.603`
[1] 0.01 0.02
$`0.72`
[1] 0.01 0.02
$`0.823`
[1] 0.01 0.02
$`0.998`
[1] 0.01 0.02