Matlab的:使用索引的逻辑删除的if-else条件语句 [英] Matlab: Remove IF-ELSE Conditional statements using Logical Indexing
本文介绍了Matlab的:使用索引的逻辑删除的if-else条件语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不明白,precisely我会怎么做这个问题,而不使用if语句或循环。
I don't understand precisely how I would do this question without using if statements or loops.
n = input ('What is the vector length? ');
y = rand(n,1);
x = rand(n,1);
p = zeros(n,1);
for i=1:n
if (y(i) > 0.5 && x(i) < 0.5) || y(i) < 0.2
p(i) = y(i) + x(i);
else
p(i) = (y(i)*x(i))^2
end
end
一)重新实现
在code只使用矢量运算和逻辑索引(即你
不能使用任何循环或分支)。
a) Reimplement the code using only vector operations and logical indexing (i.e., you cannot use any loops or branches).
推荐答案
此方法来初始化 P
-
This way and you won't be needed to initialize p
-
cond1 = (y > 0.5 & x < 0.5) | y < 0.2;
p = cond1.*(y + x) + ~cond1.*((y.*x).^2)
这篇关于Matlab的:使用索引的逻辑删除的if-else条件语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文