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

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

问题描述

Matlab中的矢量化代码比for循环运行快得多(请参见

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 Distributed Computing Server许可证).

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中的gpuArray s编写代码,并使所有内容都在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调用,因为使用gpuArray s时效率更高.

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

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

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