Home > Software design >  Simple logical condition flag MATLAB
Simple logical condition flag MATLAB

Time:11-24

I require help to develop some logic on the below data extract. I need the C2 column to toggle to '1' when C1 is '1'. Then, when C1 is '-1' the C2 column toggles to '0'. All rows in C2 between the C1 toggles (1 & -1) needs to turn to '1'.

Date           C1  C2
'24-Dec-1999'   0   0
'31-Dec-1999'   1   1
'07-Jan-2000'   0   1
'14-Jan-2000'   0   1
'21-Jan-2000'   0   1
'28-Jan-2000'   0   1
'04-Feb-2000'   -1  0
'11-Feb-2000'   0   0
'18-Feb-2000'   0   0
'25-Feb-2000'   0   0

I used the following, however it only changes the first and last entries on 31-DEC-1999 and 04-FEB-2000. How do I make it so that the entries in between (7-Jan-2000 to 28-Jan-2000) in C2 are also listed as '1'?

C2(C1==1)=1;
C2(C1==-1)=0;

CodePudding user response:

Update

The easiest way to do this is calculate the cumulative sum

C2 = cumsum(C1);

Original / Alternative

You can find the indices where C1=1 and where C1=-1, per your comments there should be an equal number of these

idxStart = find(C1=1); % Could use >0.5 to avoid numerical precision issues
idxEnd = find(C1=-1);  % Could use <-0.5 to avoid numerical precision issues

Then you just need to loop through them and make C2=1 in between

C2 = zeros(size(C1));
for ii = 1:numel(idxStart)
    C2(idxStart(ii):idxEnd(ii)-1) = 1;
end
  • Related