Changing a Function to Accept vector inputs?

6 次查看(过去 30 天)
Hello, I am having trouble making my function run with vector inputs, I am assuming that this is because of the "if" and "elseif" statements that are included in the function, and I was just wondering how I could adjust my function to accomodate for vector inputs. The code is shown below.
function y = FcnEval(x)
> if x < -2;
>y = 1./((x.^2) + 1);
> elseif (-2<=x) & (x<-1);
y = sin(x);
> elseif (-1<=x) & (x<1);
y = x^2;
> elseif (1<=x) & (x<2);
y =2;
> else x>2;
y = 1./(x+1);
end

回答(1 个)

Andrei Bobrov
Andrei Bobrov 2012-10-8
编辑:Andrei Bobrov 2012-10-8
function y = FcnEval(x)
y = zeros(size(x));
for ii = 1:numel(x)
if x(ii) < -2;
y(ii) = 1./((x(ii).^2) + 1);
elseif -2 <= x(ii) && x(ii) < -1;
y(ii) = sin(x(ii));
elseif -1 <= x(ii) && x(ii) < 1;
y(ii) = x(ii)^2;
elseif 1 <= x(ii) && x(ii) < 2;
y(ii) = 2;
else
y(ii) = 1./(x(ii)+1);
end
end
or
y = zeros(size(x));
t1 = x < -2;
y(t1) = 1./(x(t1).^2 + 1);
t2 = -2 <= x & x < -1;
y(t2) = sin(x(t2));
t3 = -1 <= x & x < 1;
y(t3) = x(t3).^2;
y(1 <= x & x < 2) = 2;
t4 = x >= 2;
y(t4) = 1./(x(t4)+1);
or
f = {@(x)1./(x.^2 + 1);@sin;@(x)x.^2;@(x)2;@(x)1./(x+1)};
[b,b]=histc(x,[-inf;-2;-1;1;2;inf]);
y = arrayfun(@(ii,jj)f{ii}(jj),b,x);

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by