필터 지우기
필터 지우기

Trying to write a function using @

조회 수: 1 (최근 30일)
ssmith
ssmith 2021년 11월 17일
댓글: John D'Errico 2021년 11월 17일
I am trying to write this function in my code but I am getting an invalid MATLAB syntax error. The equation is g(x) = sin(x)/x
Here is what I have:
g = @x sin(x)/x
g(1)
g(pi)
The g(1) and g(pi) are to be used calling the function to solve.

채택된 답변

Stephen23
Stephen23 2021년 11월 17일
편집: Stephen23 2021년 11월 17일
g = @(x) sin(x)/x;
% ^ ^ you forgot these
g(1)
ans = 0.8415
g(pi)
ans = 3.8982e-17
  댓글 수: 1
John D'Errico
John D'Errico 2021년 11월 17일
A good addendum is that IF you want this function to be vectorized, thus able to work for an entire vector or array of inputs elements, then use the ./ operator. Thus:
g = @(x) sin(x)./x;
(Without that dot in there, you will get strange results when you try to use this function on a vector.) But now we can use g on entire vectors.
g([1 2 3 4 5])
ans = 1×5
0.8415 0.4546 0.0470 -0.1892 -0.1918
The singularity at x==0 is unresolved of course, since 0/0 is undefined..
g(0)
ans = NaN
We can even plot it nicely without any arguments from MATLAB, thus
fplot(g,[-10*pi,10*pi])

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Elementary Math에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by