how define a conditional handle function?
26 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentario
Adam
el 4 de Mayo de 2017
Editada: Adam
el 4 de Mayo de 2017
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.
Respuestas (2)
Torsten
el 4 de Mayo de 2017
Editada: Torsten
el 4 de Mayo de 2017
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 comentarios
Jan
el 4 de Mayo de 2017
Editada: Jan
el 4 de Mayo de 2017
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 comentarios
Jan
el 8 de Mayo de 2017
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.
Ver también
Categorías
Más información sobre Function Creation 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!