Matlab:使用逻辑索引删除IF-ELSE条件语句

Nat*_*ins 2 arrays indexing matlab conditional vectorization

我不明白如何在不使用if语句或循环的情况下完成这个问题.

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
Run Code Online (Sandbox Code Playgroud)

a)仅使用向量运算和逻辑索引重新实现代码(即,您不能使用任何循环或分支).

Div*_*kar 5

通过这种方式,您无需初始化p-

cond1 = (y > 0.5 & x < 0.5) | y < 0.2;
p = cond1.*(y + x) + ~cond1.*((y.*x).^2)
Run Code Online (Sandbox Code Playgroud)