有人可以帮我向量化移动坡度计算。我试图消除for循环,但不确定如何这样做。

>> pv = [18 19 20 20.5 20.75 21 21.05 21.07 21.07]'; %% price vector

>> slen = 3; %% slope length

function [slope] = slope(pv , slen)
svec = (1:1:slen)';
coef = [];
slope = zeros(size(pv));

for i = slen+1 : size(pv,1)
      X = [ones(slen,1) svec];
      y = pv( (i - (slen-1)) : i );
      a = X\y;
      slope(i,1) = a(2);
end

>> slp = slope(pv,3)

slp =
        0
        0
        0
     0.75
    0.375
     0.25
     0.15
    0.035
     0.01

谢谢

最佳答案

编辑:完全更改答案以使其可扩展

function [slope] = calculate_slope(pv , slen)  %% Note: bad practice to give a function and variable the same name

svec = (1:1:slen)';
X = [ones(slen,1) svec];

%% the following two lines basically create the all the sliding windows of length slen (as a submatrix of a larger matrix)
c = repmat ( flipud(pv), 1, length(pv))
d = flipud(reshape(c(1:end-1), length(pv)-1, length(pv) + 1));

%% then run MATLAB solver with all windows simultaneously
least_sq_result = X\d( end - slen + 1:end, (slen+1):end);
slope = [zeros(slen-1, 1); least_sq_result(2,:)'];  %% padding with zeros is optional

编辑:固定交换的索引

10-04 17:40