Changing a Function to Accept vector inputs?
조회 수: 7 (최근 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
댓글 수: 0
답변 (1개)
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);
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!