필터 지우기
필터 지우기

how define a conditional handle function?

조회 수: 30 (최근 30일)
xosro
xosro 2017년 5월 4일
댓글: Jan 2017년 5월 8일
As you know, for
f=@(x) sin(x)/x;
we get f(0)=NaN
if we would like get f(0)=0
again with
f=@(x) (x==0)*0+(x~=0)*sin(x)/x;
we will receive f(0)=NaN.
how can i dominate this problem?
  댓글 수: 1
Adam
Adam 2017년 5월 4일
편집: Adam 2017년 5월 4일
Please try to ensure you format your question in a readable way. The
if true
end
lines should not keep appearing around every bit of code. I don't really know why the '{} Code' button is setup to do this as so many people end up with it included in their code. Also don't include the lines of your question in the middle of one large code block - it is very confusing to read and separate out what is actually code and what is part of the question information.
I did the editing for you this time.

댓글을 달려면 로그인하십시오.

답변 (2개)

Torsten
Torsten 2017년 5월 4일
편집: Torsten 2017년 5월 4일
function main
x = [3 7.5 0 -0.03];
y = f(x)
function y = f(x)
i = find(x==0);
x(i) = 1;
y = sin(x)./x;
y(i) = 0;
end
Best wishes
Torsten.
  댓글 수: 3
Jan
Jan 2017년 5월 4일
편집: Jan 2017년 5월 4일
Or a little bit simpler:
function y = f(x)
y = sin(x) ./ x;
y(x==0) = 0;
end
@xosro: Do not confuse a "handle function" with an "anonymous function", which is accessed by a "function handle".
Torsten
Torsten 2017년 5월 4일
편집: Torsten 2017년 5월 4일
My guess is that this function cannot be defined as a "one-liner" as
f=@(x)....
Best wishes
Torsten.

댓글을 달려면 로그인하십시오.


Jan
Jan 2017년 5월 4일
편집: Jan 2017년 5월 4일
A function (see Torsten's answer) will be nicer and more efficient than an anonymous function. But if you realy have any good reasons:
f = @(x) sin(x) / [Inf(x==0), x(x~=0)];
This works for scalar x only. This would be better, because it is immediately clear, what it does:
function y = f(x)
y = sin(x) ./ x;
y(x==0) = 0;
end
  댓글 수: 7
xosro
xosro 2017년 5월 5일
@Jan Simon: Ok, "nested function" is a good idea, but for using variables as inputs, i had some limitation so i have used "global variables" for using variables between scripts.
Thank you and other dears
Jan
Jan 2017년 5월 8일
Avoid global variables. They cause more troubles than they solve. If you do not want to provide too many arguments, store them in a struct.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Performance and Memory에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by