我正在寻找一种更面向矩阵/应用的方式来编写 R 中的状态机,而不是我在这里使用 for 循环和一堆 if 语句所做的?这在 R 中是否可能,您需要知道机器的先前状态?
A1 和 A2 都为 1 时下机布防,B1 和 B2 都为 1 时布防撤防。一般情况下,A1、A2、B1 和 B1 之间没有已知的关系。如果没有满足任何条件,则保持先前的状态。
是否可以在 R 中进行这种计算而无需 for 循环逐个遍历矩阵?如果是这样,请创建一些计算 S1a 的代码。谢谢。
[[编辑以简化一点]]
Mach1 = matrix(data=0, nrow = 24, ncol = 6)
colnames(Mach1)=c("A1","A2","B1","B2","S1","S1a")
Mach1[,"A1"] <- c(0,0,0,1,1,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0)
Mach1[,"A2"] <- c(0,0,0,0,0,1,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0)
Mach1[,"B1"] <- c(0,0,1,1,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,1,0,0)
Mach1[,"B2"] <- c(0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1)
for (i in 2:nrow(Mach1)){
Prev = Mach1[(i-1),"S1"]
Prev = ifelse(is.na(Prev), 0, Prev)
Arm = ((Mach1[i,"A1"] ==1) && (Mach1[i,"A2"] == 1))
Disarm = ((Mach1[i,"B1"] == 1) && (Mach1[i,"B2"] == 1))
if ((Prev == 0) && (Arm)){ #Turn on
Mach1[i,"S1"] <- 1
print(paste(i, "Armed"))
} else if ((Prev == 1) && (Disarm)){ #Turn off
Mach1[i,"S1"] <- 0
print(paste(i, "Disarmed"))
} else {
Mach1[i,"S1"] <- Prev
print(paste(i, "---"))
}
}
rm(Arm, Disarm, Prev, i)