Matlab(或 Octave)中网格的矢量化 [英] Vectorization for meshgrid in Matlab (or Octave)

查看:23
本文介绍了Matlab(或 Octave)中网格的矢量化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Matlab 中的矢量化代码运行速度比 for 循环快得多(参见 Octave 在单台机器上的并行计算 -- 封装和示例用于 Octave 中的具体结果)

Vectorized code in Matlab runs much faster than a for loop (see Parallel computing in Octave on a single machine -- package and example for concrete results in Octave)

话虽如此,有没有办法在 Matlab 或 Octave 中对接下来显示的代码进行矢量化?

With that said, is there a way to vectorize the code shown next in Matlab or Octave?

x = -2:0.01:2;
y = -2:0.01:2;
[xx,yy] = meshgrid(x,y);
z = sin(xx.^2-yy.^2);

推荐答案

正如@Jonas 所指出的,MATLAB 中有几个可用的选项,哪个效果最好取决于几个因素,例如:

As pointed out by @Jonas, there are a few options available in MATLAB, and which works best depends on a few factors such as:

  • 您的问题有多大
  • 您有多少台机器可用
  • 你有 GPU
  • MATLAB 是否已经对操作进行了多线程处理

现在 MATLAB 中的许多元素操作都是多线程的 - 在这种情况下,使用 PARFOR 通常没什么意义(除非您有多台机器和 MATLAB 分布式计算服务器许可证可用).

Many elementwise operations are multithreaded in MATLAB now - in which case, there's generally little point using PARFOR (unless you have multiple machines and MATLAB Distributed Computing Server licences available).

真正需要多台机器内存的大问题可以受益于分布式数组.

Truly huge problems that need the memory of multiple machines can benefit from distributed arrays.

如果您的问题的大小和类型适合 GPU 计算,则使用 GPU 可以击败单台机器的多线程性能.矢量化代码往往最适合通过 GPU 进行并行化.例如,您可以像这样使用 Parallel Computing Toolbox 中的 gpuArrays 编写代码,并让所有内容都在 GPU 上运行.

Using the GPU can beat the multithreaded performance of a single machine if your problem is of a suitable size and type for GPU computation. Vectorized code tends to be the most natural fit for parallelization via the GPU. For example, you could write your code using gpuArrays from Parallel Computing Toolbox like so and have everything run on the GPU.

x = parallel.gpu.GPUArray.colon(-2,0.01,2);
y = x;
[xx,yy] = meshgrid(x,y); % xx and yy are on the GPU
z = arrayfun( @(u, v) sin(u.*u-v.*v), xx, yy );

我将那里的最后一行转换为 arrayfun 调用,因为使用 gpuArrays 时效率更高.

I converted the final line there into an arrayfun call as that is more efficient when using gpuArrays.

这篇关于Matlab(或 Octave)中网格的矢量化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆