我编写了下面的MATLAB代码。我想知道如何在不使用for循环的情况下优化它。如有任何帮助,我将不胜感激。
MATLAB代码:
%Some parameters:
s = 50;
k = 50;
r = 0.1;
v = 0.2;
t = 2;
n=10000;
% Calculate CT by calling EurCall function
CT = EurCall(s, k, r, v, t, n);
%Function EurCall to be called
function C = EurCall(s, k, r, v, t, n)
X = zeros(n,1);
hh = zeros(n,1);
for ii = 1 : n
X(ii) = normrnd(0, 1);
SS = s*exp((r - v^2/2)*t + v*X(ii)*sqrt(t));
hh(ii) = exp(-r*t)*max(SS - k, 0);
end %end for loop
C = (1/n) * sum(hh);
end %end function
矢量化方法:
这是一个矢量化的方法,我认为它复制了与原始脚本相同的功能。这个例子将X
声明为大小为n × 1的向量,而不是循环。通过使用元素乘法.*
,我们可以有效地计算出剩余的向量SS
和hh
,而不需要遍历索引。在这种情况下,SS
和hh
也将是大小为n × 1的向量。我同意上面的评论,MATLAB的for循环不再是固有的慢。
%Some parameters:
s = 50;
k = 50;
r = 0.1;
v = 0.2;
t = 2;
n=10000;
% Calculate CT by calling EurCall function
[CT] = EurCall(s, k, r, v, t, n);
%Function EurCall to be called
function [C] = EurCall(s, k, r, v, t, n)
X = zeros(n,1);
hh = zeros(n,1);
mu = 0; sigma = 1;
%Creating a vector of normal random numbers of size (n by 1)%
X = normrnd(mu,sigma,[n 1]);
SS = s*exp((r - v^2/2)*t + v.*X.*sqrt(t));
hh = exp(-r*t)*max(SS - k, 0);
C = (1/n) * sum(hh);
end %end function
使用MATLAB R2019b运行