0

I'm attempting to find values in the array x which are <= p, and perform one set of operations on those specific values where the condition holds true, and another set of operations otherwise. Below is essentially what I am trying to achieve, and I am aware that it doesn't work. Is there a way to achieve what I want via vector operations rather than using a for loop to iterate through each value?

if x <= p 
        y = (m/(p^2)).*(2*p.*x - x.^2);
        theta = atan((m/(p)).*(p - x));
    else
        y = (m/((5-p)^2)).*((1-p) + 2*p.*x - x.^2)
        theta = atan((2*m/((1-p)^2)).*(p - x));
    end
chssu
  • 55
  • 4
  • Yes, use logical indexing. Create `y = zeros(size(x))`, then call `y = fun( ...x(x<=p))` on just those values and of course the same for `x(x>p)` – Adriaan Mar 23 '22 at 14:11
  • @Adriaan thank you, it is closer to working now, however, doing the same for ```x(x>p)``` results in the ```y``` array being overwritten – chssu Mar 23 '22 at 14:46
  • 1
    Don't assign to `y`, assign into `y`: `I = x<=p; y(I) = fun(...x(I)); y(~I) = fun(...x(~I));`. – Cris Luengo Mar 23 '22 at 16:48

0 Answers0