Info

This question is closed. Reopen it to edit or answer.

Vectorization

2 views (last 30 days)
Andrea
Andrea on 27 Dec 2011
Closed: MATLAB Answer Bot on 20 Aug 2021
Hi,
I have a while loop that takes quite a long time to be calculated (especially when used in combination with ga optimization...I am not sure why) and that I would like to replace with some vectorization.
Here it goes:
while i< end_iteration
if G(i,3)/G(i-lookback_period,6) -1 > threshold_1
s(i: i+ hold_length) = 1;
i = i + hold_length;
elseif G(i,3)/G(i-lookback_period,6) -1 < -threshold_2
s(i: i+ hold_length) = -1;
i = i + hold_length;
else
s(i) = 0;
i = i+1;
end
end
s(1:hold_length)=0;
G is a 7 columns matrix filled with doubles, with around 1million rows. Part of the problem can be solved by doing:
lookback_vector = [zeros(lookback_period,size(G,2));G(lookback_period+1:end,:)];
s(G(:,3)/lookback_vector(:,6)-1 > threshold_1)=1;
s(G(:,3)/lookback_vector(:,6)-1 < -threshold_2)=-1;
s(1:hold_length)=0;
The problem I have then is how to fill with 1s and -1s the value from "i" to "i+hold", also because if say "i_1" < "i_2" <= "i_1 + hold" (with "i_1" and "i_2" being two indices satisfying the if or elseif conditions), then "i_2" shouldn't be a triggering condition.
Any help is appreciated.
Thanks
  2 Comments
Jan
Jan on 27 Dec 2011
What is "hold"? It is recommended not to overwrite the names of built-in functions.
Did you pre-allocate "s" sufficiently? This is essential.
Andrea
Andrea on 27 Dec 2011
Thanks for the reply. "hold" is a scalar with positive values. I take your advice and let's call it "hold_length" from now on. "s" has been preallocated to be zeros(end_iteration + hold_length, 1).
And sorry, I don't think your solution solves the problem. If s(index) has two consecutive 1s (or, as written above,"i_1" < "i_2" <= "i_1 + hold_length", with "i_1" and "i_2" being two indices satisfying the if or elseif conditions), it becomes a mess.

Answers (1)

Jan
Jan on 27 Dec 2011
cumsum help for such cases usually:
index = find((G(:,3) / lookback_vector(:,6)-1) > threshold_1);
s(index) = 1;
s(index + hold_length) = -1;
s = cumsum(s);
Care for overlapping sections.
[EDITED]: If there are overlapping sections, this might be helpful: FEX: mcolon.
  3 Comments
Andrea
Andrea on 27 Dec 2011
Is there a way to go for a second pass and zeroing out all the "fake" triggers?
Something like s(index : index + hold_length-1) = 0 would work?
Jan
Jan on 27 Dec 2011
This was meant by "overlapping sections". See [EDITED]

Community Treasure Hunt

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

Start Hunting!