Is there a way of getting this done more efficiently ?

1 view (last 30 days)
I have the following code and it is taking a very long time to go through it... I dont think its an infinite loop but it is as follows:
Y = zeros(1069,30658);
D1 = LagOp({0,1,1,1},'Lags',[0,1,2,1]);
for n = 2:30658;
for j = 2:1063
if filter(D1,Ret((D1.Degree + j),n),'Initial',Ret(2:D1.Degree,n)) < 0;
Y(j+1,n) = -1*Ret(j+1,n);
else
Y(j+1,n)=Ret(j+1,n) ;
end
end
end
Basically I want to flip the sign of the current element in the matrix if the previous 3 elements before it add up to being less than 0. Otherwise to leave it alone. Could it be the ... else statement causing the trouble here ?
Thanks,
  6 Comments
Walter Roberson
Walter Roberson on 20 Jan 2016
Some kinds of filters are implemented using convolutions.
Putsandcalls
Putsandcalls on 20 Jan 2016
I dont know why I keep getting an error saying that it has a dimension mismatch. So is the first part itself suppose to be a separate statement or is the entire 2 parts suppose to be a nested for loop? When I try the nested for loop, it tells me a dimension mismatch. While do a single for loop just gives me no changes.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 20 Jan 2016
Edited: Walter Roberson on 20 Jan 2016
Without taking lags into account,
Y(:,n) = Ret(:,n);
t = conv(Y(:,n), [1 1 1], 'valid');
mask = [false(3,1); t(1:end-1)<0];
Y(mask,n) = -Y(mask,n);
This version uses the original values in each step of the calculation, not the potentially-flipped values.
To do everything at once,
t = conv(Ret, [1 1 1].', 'valid');
mask = [false(3, size(Ret,2)); t(1:end-1,:) < 0];
Y = Ret;
Y(mask) = -Y(mask);
  6 Comments
Putsandcalls
Putsandcalls on 20 Jan 2016
Thanks a lot, but if you have time to spare, I hope you can answer my question :)

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!