Changing a Function to Accept vector inputs?
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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
0 comentarios
Respuestas (1)
Andrei Bobrov
el 8 de Oct. de 2012
Editada: Andrei Bobrov
el 8 de Oct. de 2012
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);
0 comentarios
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!