Possible Vectorization using If Statements in MATLAB

隐身守侯 提交于 2020-02-04 09:34:57

问题


Suppose I have the following column vectors as

res1 = -0.81              res2 =  0.61
        0.1                      -0.4
       -0.91                      0.62
        0.2                      -0.56
        0.63                     -0.72

and I have two fixed constant D = 0.5. Now suppose an element of res1 is called X and an element of res2 is called Y. I have the following conditions

if (X > D && Y < -D)
     output = 1
elseif (X < -D && Y > D)
     output = -1
else
     output = 0
end

My question is this:

Is it possible to "vectorize" these conditions to iterate over the entire vectors res1 and res2, such that my output vector would give (for example) :

 output = -1
           0
          -1
           0
           1

?

I know I can do it via a loop, but I would prefer to avoid it since these vectors are actually quite large (>10000). I have attempted to use logical indexing, but to no avail (unless I'm implementing it wrong).

Any help would be appreciated!


回答1:


You can use logical arrays to replace the conditional statements and scale them with appropriate scaling factors for the final output -

%// Logical arrays corresponding to the IF and ELSEIF conditional statements
case1 = res1>D & res2<-D
case2 = res1<-D & res2>D

%// Get the final output after multiplying each case with the
%// scaling factors 1 and -1 respectively. 
%// The default value of `zero` for the ELSE part is automatically taken 
%// care of because we are using logical array of ones and zeros anyway
output = case1 + -1*case2 %// or simply case1 - case2

Sample run -

>> res1
res1 =
   -0.8100
    0.1000
   -0.9100
    0.2000
    0.6300
>> res2
res2 =
    0.6100
   -0.4000
    0.6200
   -0.5600
   -0.7200
>> output
output =
    -1
     0
    -1
     0
     1


来源:https://stackoverflow.com/questions/28232308/possible-vectorization-using-if-statements-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!