Mathematica 模式匹配实验

结论:
利用模式匹配,可以避免循环,完成对数组中特定元素的操作,方法有多种,但是速度有所差别。

  1. 在不用到特殊函数的场合,可以考虑使用Compile加速(有C编译器时优先编译为C,另外可加上并行运算指令);
  2. 不能编译的话,优先使用Map函数;

  3. 与Matlab一样,多考虑向量化编程;

  4. 尽量减少中间变量;避免引入副作用。

此问题来源于知乎上的一次讨论:
「Mathematica中已知位置列表,如何直接对目标元素进行操作?」

P.S.
Matlab 的对应代码如下:

clear all
N = 40;
tic
vc = zeros(N,N,N,N);
for k1 = 0:N-1
for k2 = 0:N-1
for m = 0:N-1
for n = 0:N-1
c1 = cos (pi/N * (m+1/2) * k1);
c2 = cos (pi/N * (n+1/2) * k2);
c = c1 * c2;
vc(k1+1,k2+1,m+1,n+1) = ((c<0)*10 + (c>0))*c;
end
end
end
end
vc;
TotalTime = toc

Advertisements
  1. No trackbacks yet.

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s