我需要使用feval来评估值向量的函数。该函数定义如下:
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
以下解决方案不起作用:
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
确实,有:
p(1,:)=[2 3 4 5];
p(2,:)=[1 0 7 8];
hs=@s;
f=feval(hs, p(1,:), p(2,:));
我得到f =
-0.500000000000000 -0.500000000000000 -0.500000000000000
而不是4值向量。
答案 0 :(得分:2)
看看这种逻辑索引方法是否适合您 -
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;