Search code examples
matlabloopsif-statementindexingfinancial

Calculations on cell pairs that meet multiple pre-defined criteria?


My goal: Depending on which of the 5 scenarios is prevalent in each row, make the calculation following the if statement. End result should be 1 column, including the outcome of each row calc.

What I tried so far:

CalcOutcome = zeros(554,1);
  for k=height(MomPF)
        if MomPF.L_sum4t<0 & MomPF.U_sum4t>0           
            % make calc for every row but end result should only be 1 column
            % with the calc outcomes
            CalcOutcome=(-1)*MomPF.L_sum4t{k}*0.5 + MomPF.U_sum4t{k}*0.5;
        elseif MomPF.L_sum4t<0 & MomPF.U_sum4t<0
            CalcOutcome=(-1)*MomPF.L_sum4t{k}*1;
        elseif MomPF.L_sum4t>0 & MomPF.U_sum4t>0
            CalcOutcome=MomPF.U_sum4t{k}*1;
        elseif MomPF.L_sum4t>0 & MomPF.U_sum4t<0
            CalcOutcome=MomPF.L_sum4t{k}*0.5 + (-1)*MomPF.U_sum4t{k}*0.5;
        elseif MomPF.L_sum4t==0 & MomPF.U_sum4t==0
            CalcOutcome=0          
        end
   end

Table: enter image description here


Solution

  • As others have mentioned, it appears the indexing is the problem. That said, you don't need to loop -- you should be able to do all of this at once with table indexing. For example, something like:

    idx = (MomPF.L_sum4t < 0) & (MomPF.U_sum4t > 0); CalcOutcome(idx) = -0.5*MomPF.L_sum4t(idx) + 0.5*MomPF.U_sum4t(idx);

    And then rinse and repeat for the other conditions.