有没有二维“地图”?等价于Matlab?
我试图通过将一个函数应用于两个向量的元素的所有组合来生成一个矩阵 - 像这样:
A(i,j) = fun(X(i), Y(j));
我发现的最佳解决方案是循环所有 i 和 j,但我知道这在 Matlab 中是不好的风格。有什么建议吗?
I'm trying to generate a matrix by applying a function to all combinations of elements of two vectors -- something like this:
A(i,j) = fun(X(i), Y(j));
Best solution I've found is to loop over all i and j, but I know that's bad style in Matlab. Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这基本上就是 MESHGRID 的用途。它将值向量复制到网格中,然后可以将函数应用于这些网格点。您通常可以利用矩阵和逐元素数组运算来避免使用 for 循环对生成的网格执行某些计算。下面是一个示例:
请注意 MESHGRID 的第一个输入(即
X
)被视为沿列运行,而第二个输入(即Y
)被视为沿行运行。如果X
和Y
表示笛卡尔坐标并且矩阵A
将被绘制为 3-D 曲面或网格,则通常需要这样做。但是,如果您想要这种行为,您也可以使用函数 NDGRID ”翻转”。这是 NDGRID 的相同示例:请注意
A 现在是 4×5 矩阵,而不是 5×4 矩阵。
This is basically what MESHGRID is for. It replicates vectors of values into meshes, and a function can then be applied to those meshed points. You can usually take advantage of matrix and element-wise array operations to avoid using a for loop to perform certain computations on the resulting meshes. Here's an example:
Notice that the first input to MESHGRID (i.e.
X
) is treated as running along the columns, while the second input (i.e.Y
) is treated as running down the rows. This is generally desired ifX
andY
represent Cartesian coordinates and the matrixA
is going to be plotted as a 3-D surface or mesh. However, you could also use the function NDGRID if you want this behavior "flipped". Here's the same example with NDGRID:Notice that
A
is now a 4-by-5 matrix instead of a 5-by-4 matrix.