Gonzague
Gonzague

Reputation: 39

Remove IF-ELSE conditional statements and Vectorization

I need to use feval to evaluate a function on a vector of values. The function is defined by:

function v = s(x,y)
if y>=0.5
    if (-2*(x-3/4)+(y-1/2))<0
        v=-0.5;
    else
        v=1.5;
    end
else
    v=max( -0.5,min( 1.5,(x-3./4)/(y-1./2) ) );
end
end

The following solution does not work:

function v = s(x,y)
ind1=(y>=0.5); 
ind2=(-2*(x(ind1)-3/4)+(y(ind1)-1/2)<0);
ind3=(-2*(x(ind1)-3/4)+(y(ind1)-1/2)>=0);
v(ind2)=-0.5;
v(ind3)=1.5;
v(~ind1)=max( -0.5,min( 1.5,(x(~ind1)-3./4)/(y(~ind1)-1./2) ) );
end

Indeed, with:

p(1,:)=[2 3 4 5];
p(2,:)=[1 0 7 8];
hs=@s;
f=feval(hs, p(1,:), p(2,:));

I get f=

-0.500000000000000  -0.500000000000000  -0.500000000000000

instead of a 4-valued vector.

Upvotes: 1

Views: 160

Answers (1)

Divakar
Divakar

Reputation: 221504

See if this logical indexing approach works for you -

function v = s(x,y)

cond1 = y>=0.5;
cond2 = (-2*(x-3/4)+(y-1/2))<0;

val = max( -0.5,min( 1.5,(x-3./4)./(y-1./2) ) );
v = -0.5.*(cond1&cond2) + 1.5.*(cond1&~cond2) + ~cond1.*val;

return;

Upvotes: 2

Related Questions