matlab高性能代码编写-meshgrid和ndgrid
- UID
- 1029342
- 性别
- 男
|
matlab高性能代码编写-meshgrid和ndgrid
这个技能是比较常用和有效,一方面能提高效率,另一方面能够让代码更漂亮一些。:)
一般来说在Matlab中,for很多情况下可以被meshgrid或者ndgrid代替,效率会提高很多。
%% meshgird 代替 for 提高效率
%目标将每个a与每个b相加
a = 1:20;
b = 6 : 10;
t1 = 0;
t2 = 0;
p1 = zeros(length(b),length(a));
[A B] = meshgrid(a,b);
for num = 1 :10000
tic;
for n = 1 : length(a)
for m = 1 : length(b)
p1((n-1)*length(b) + m) = a(n) + b(m);
end
end
t1= toc + t1;
tic;
p2 = A + B;
t2=toc + t2;
end
ratio = t1/t2;
if (nnz(p1-p2) == 0)
disp('p1 equals p2');
end
msg = sprintf('Loop 2 is %2.1fx faster than loop 1',ratio);
disp(msg);
%% ndgrid 代替 n 重 for
%目标将 a,b,c 循环相加
a = 1:20;
b = 6 : 10;
c = 1:10;
t1 = 0;
t2 = 0;
p1 = zeros(length(a),length(b),length(c));
[A B C] = ndgrid(a,b,c);
for num = 1 :1000
tic;
count = 0;
for n = 1 : length(c)
for m = 1 : length(b)
for l = 1 : length(a)
p1(l,m,n) = a(l) + b(m) + c(n);
end
end
end
t1= toc + t1;
tic;
p2 = A + B + C;
t2=toc + t2;
end
ratio = t1/t2;
if (nnz(p1-p2) == 0)
disp('p1 equals p2');
end
msg = sprintf('Loop 2 is %2.1fx faster than loop 1',ratio);
disp(msg); |
|
|
|
|
|