Search code examples
arraysmatlab

Are there any drawbacks using logical instead of integer arrays and values in arithmetic operations?


For operations involving integers, is a vector of logical values equivalent to a vector of integers taking appropriate values of 0 and 1?

Will I run into unexpected consequences if I make computations on or apply functions to logical objects instead of integer objects?


Solution

  • It really depends on the case, but as always in programming: the explicit conversion of variables is better than implicitly!

    Here a simple example, where you could see a difference:

    x = [0 1 0 1 0]      %// 0     1     0     1     0
    y = logical(x)       %// 0     1     0     1     0
    
    y(y) = 5             %// 0     1     0     1     0
    x(y) = 5             %// 0     5     0     5     0
    y(x) = 5             %// error
    x(x) = 5             %// error
    

    So when it comes to indexing the indexed variable on the left hand side of the assignment determines the type of the output. So as long as you can ensure, that your output is always double, you shouldn't run into problems.

    Have a look at this more complex example:

    z = double([0 0 0 0 0])
    z(y) = x(y) + y(y)
    

    the first summand is double, the second is logical. But as they are part of an arithmetic operation both summands are treated double. As z is double as well, the result is double.

    z =
    
         0     2     0     2     0
    

    Now consider the following:

    z = logical([0 0 0 0 0])
    z(y) = x(y) + y(y)  
    

    again the first summand is double, the second is logical. And again they are treated double. But z is logical, so the actually double result is converted to logical.

    z =
    
         0     1     0     1     0