我正在尝试用matlab做一个等高线图。然而,语法似乎是正确的,但matlab正在永远地绘制这个,因为矩阵可能非常大。
请建议我该怎么做。
以下是我的代码:
s = 10000000;
eta_gamma = zeros(s/10000);
for g1= 1:10000:s
for g2 = 1:10000:s
eta_gamma(g1,g2) = floor((1000000000 - g1 - g2)/ (200000*(1 + floor(-0.001 + 20000*(0.001 + (0.1 + 0.9/ (1 + (-1000000 + 5000000* lambertw(power(exp(1), 0.2 + g1/5.E6)/5.))/1.E6))/ 100.))) + 75000*(1 + floor(-0.001 + 20000*(0.002 + (0.2 + 0.8/ (1 + (-8000000 + 4000000* lambertw(2* power(exp(1),2 + g2/4.E6)))/8.E6)) /200.)))));
end
end
figure
contour(eta_gamma)
答案 0 :(得分:4)
似乎瓶颈是因为那里有两个重型嵌套循环。解决方案当然是vectorization
,目的是删除这两个循环。可以在此处使用vectorization
,bsxfun
的最佳工具之一。接下来列出的最终矢量化实现在我的结尾处以 1.323403 seconds
运行,而原始的嵌套循环版本正在耗尽并耗尽大量内存。这是代码 -
%// Input parameter
s = 10000000;
%// Define 1D arrays corresponding to each nested loop
G1 = 1:10000:s;
G2 = 1:10000:s;
%// Perform the calculations in a vectorized manner in three parts:
%// Part1: Do vectorized "1000000000 - g1 - g2"
p1 = 1000000000 - bsxfun(@plus,G1,G2.'); %//'
%// Part2: Do vectorized operations for everything involving G1 (nested loop-I)
p2 = 200000*(1 + floor(-0.001 + 20000*(0.001 + (0.1 + 0.9./ (1 + (-1000000 + ...
5000000* lambertw(power(exp(1), 0.2 + G1/5.E6)/5.))./1.E6))/ 100.)));
%// Part3: Do vectorized operations for everything involving G2 (nested loop-II)
p3 = 75000*(1 + floor(-0.001 + 20000*(0.002 + (0.2 + 0.8./(1 + (-8000000 + ...
4000000* lambertw(2* power(exp(1),2 + G2/4.E6)))/8.E6)) /200.)));
%// Finally combine all parts into a 2D array output, which would be eta_gamma
eta_gamma_vectorized = floor(p1./bsxfun(@plus,p2,p3.')); %//'
%// Plot results
figure, contour(eta_gamma_vectorized)
这是情节结果 -