Question

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

a) Reimplement the code using only vector operations and logical indexing (i.e., you cannot use any loops or branches).

Was it helpful?

Solution

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top