Search code examples
matlabif-statementmergevectorizationoctave

Calling a vectorized operation in Octave for multiple output


I would like to make a vectorized ifelse/merge operation on some data. To avoid unnecessary comparisons, I would like to obtain a result by calling ifelse command only once. Here is my example code:

aaa = [90 80 70 60];
bbb = [10 15 20 30];
ccc = [ 0  3  6  9];
res = ifelse(ccc > 5, {[aaa bbb]}, {[aaa*-1 bbb*-1]})

Since I could run the ifelse command with cell arrays, I am getting the repetitive results as below:

{
  [1,1] = -90  -80  -70  -60  -10  -15  -20  -30
  [1,2] = -90  -80  -70  -60  -10  -15  -20  -30
  [1,3] =  90   80   70   60   10   15   20   30
  [1,4] =  90   80   70   60   10   15   20   30
}

However, the result what I want from ifelse command is as below:

[-90 -80 70 60]
[-10 -15 20 30]

Actually, I can do it by calling the ifelse command twice, as follows:

res1 = ifelse(ccc > 5, aaa, aaa*-1)
res2 = ifelse(ccc > 5, bbb, bbb*-1)

However, I do not want to call it twice, because the mask is the same for both. So, if there is a way to get this result in one call of the ifelse command in Octave or Matlab?


Solution

  • You can define your mask as an anonymous function and apply it with bsxfun:

    mask = @(x, y) ifelse(y > 5, x, x*-1);
    bsxfun(mask, [aaa; bbb], ccc)
    

    Output:

    ans =
    
      -90  -80   70   60
      -10  -15   20   30