Function outputs NaN for a cell which is assigned a separate value?

I created the following function:
function [x] = f(y)
x = (y==0).*1+(y~=0).*(1./y);
With the following input, it returns this:
f([-3:3])
ans =
-0.3333 -0.5000 -1.0000 NaN 1.0000 0.5000 0.3333
The value should be 1 when y == 0 but it shows NaN instead (assumably by evaluating 1./y when y == 0)

 채택된 답변

VBBV
VBBV 2020년 11월 9일
since you want 1 when y is zero, you need something like
y(y==0) = 1;
y(y~=0) = 1./y;
x = y;

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Interpolation of 2-D Selections in 3-D Grids에 대해 자세히 알아보기

제품

릴리스

R2020b

태그

질문:

2020년 11월 9일

답변:

2020년 11월 9일

Community Treasure Hunt

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

Start Hunting!

Translated by