问题
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