在MATLAB中使用If语句可能的向量化

在MATLAB中使用If语句可能的向量化

本文介绍了在MATLAB中使用If语句可能的向量化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我具有以下列向量

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

,我有两个固定常数D = 0.5.现在假设res1的元素称为X,而res2的元素称为Y.我有以下条件

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

我的问题是这个

是否可以将这些条件向量化"以遍历整个向量res1res2,这样我的输出向量就可以给出(例如):

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

?

我知道我可以通过循环来做到这一点,但是我宁愿避免这样做,因为这些向量实际上很大(> 10000).我曾尝试使用逻辑索引,但无济于事(除非我实施错误).

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).

任何帮助将不胜感激!

推荐答案

您可以使用 logical arrays 替换条件语句,并使用适当的比例因子对它们进行缩放以用于最终输出-

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

这篇关于在MATLAB中使用If语句可能的向量化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 22:30