R 中的 for 循环之内或之外 - 计算矩阵的对角积
我试图找到 20x20 矩阵中 2 位数字的最大对角积。
这给出了一条错误消息:
i <- 17:1
z <- for (j in 1:(18-i))
{b <- max ((x[i,j]*x[i+1,j+1]*x[i+2,j+2]*x[i+3,j+3]))}}
但这没有:
z <- for (i <- 17:1)
{for (j in 1:(18-i))
{b <- max ((x[i,j]*x[i+1,j+1]*x[i+2,j+2]*x[i+3,j+3]))}}
但第二个版本给我的数字太小了。为什么第一个不起作用,我认为它会产生正确的答案,但我不明白错误消息。
I'm trying to find the maximum diagonal product of 2 digit numbers in a 20x20 matrix.
This gives an error message :
i <- 17:1
z <- for (j in 1:(18-i))
{b <- max ((x[i,j]*x[i+1,j+1]*x[i+2,j+2]*x[i+3,j+3]))}}
But this doesn't:
z <- for (i <- 17:1)
{for (j in 1:(18-i))
{b <- max ((x[i,j]*x[i+1,j+1]*x[i+2,j+2]*x[i+3,j+3]))}}
but the second version gives me a number too small . Why does the first one not work, i think it would yield the correct answer, but i don't understand the error message.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这看起来是错误的。
您不能将
for
循环的结果分配给变量。 max() 是在一个标量变量上,这是无意义的。最后,未指定矩阵 x 。我会用更小的东西重试,甚至可能将一些临时结果打印到屏幕上。先走再跑仍然是个好建议。稍后您仍然可以矢量化以获得冲刺解决方案。
This looks wrong.
You cannot assign the result of a
for
loop to a variable. Andmax()
is over a scalar variable which is nonsense. Lastly, matrixx
isn't specified. I'd retry with something smaller, and maybe even print some interim results to screen.Walk before you run is still good advice. Later you can still vectorise for a sprint solution.
实际上,与 Dirk 相反,我认为您应该尽快了解 R 中的矢量化。您尝试实现的循环结构远非最佳,而且实际上是多余的。仅应在非常特殊的情况下使用 for 循环。查看此问题中的讨论。查看一下便利函数的帮助文件,例如
diag()
、combn()
、prod()
和apply()
。将它们组合起来做你想做的事情很容易:
编辑:你使用数据框,但你可以使用
as.matrix(x)
将其轻松转换为矩阵。Actually, contrary to Dirk I believe that you should be aware of vectorization in R as soon as possible. The loop structure you try to implement is far from optimal, and actually redundant. Using a for-loop should be done only in very specific cases. Check the discusison in this question. Take a look at the help files of convenience functions like
diag()
,combn()
,prod()
andapply()
.It's easy to combine them to do what you want :
Edit : You use a data frame, but you can use
as.matrix(x)
to convert this easily to a matrix.