필터 지우기
필터 지우기

Help with nesting subfunctions?

조회 수: 2 (최근 30일)
Tyler
Tyler 2012년 9월 25일
I have an assignment that requires me to use a nested subfunction to produce a plot, and am not sure how to incorporate it. The exact problem states:
Recall Euler’s formula from analytical calculus: ei·x = cos(x) + i · sin(x), where i is the imaginary unit. A slight rearrangement yields:
cos(x) = ei·x i · sin(x)
Create a nested subfunction that accepts one input argument x (which may be
a vector) and returns the cos function defined as above. Call this function and plot its output from −π ≤ x ≤ π using π/100 increments. Label axes and title it ”Euler Output”.
So far, I have not even been able to do this without a nested subfunction. MATLAB tells me that, "Subscript indices must either be real positive integers or logicals," but the given equation clearly needs to make use of imaginary roots.
  댓글 수: 3
Tyler
Tyler 2012년 9월 25일
%% Part 1 - Euler
x=-pi:pi/100:pi;
cos(x)=exp(1i.*x)-1i*sin(x);
figure1(x,cos(x));
title('Euler Output')
And that returns with
"Subscript indices must either be real positive integers or logicals."
Tyler
Tyler 2012년 9월 25일
I know that isn't a nested function at all, but shouldn't that still work just so I can get an idea of which direction to go?

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

채택된 답변

Wayne King
Wayne King 2012년 9월 25일
편집: Wayne King 2012년 9월 25일
Your problem is here:
cos(x)=exp(1i.*x)-1i*sin(x);
You should spend some time reading the MATLAB Getting Started material, but you just assign the output to a variable.
cosx = exp(1i*x)-1i*sin(x);
Of course you have another problem with figure1( ) unless you have written a function called figure1().
  댓글 수: 2
Tyler
Tyler 2012년 9월 25일
How would I go about making that an anonymous function and calling it through the script? Just by making the above:
h=@cosx exp(1i*x)-1i*sin(x);
?
What benefit does that have when writing code?
Wayne King
Wayne King 2012년 9월 25일
cosx =@(x) exp(1i*x)-1i*sin(x);
that gives you a function handle.
Then you can do:
x = -pi:0.01:pi;
y = cosx(x);

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by