필터 지우기
필터 지우기

How to properly use nargin

조회 수: 8 (최근 30일)
Brendan Clark
Brendan Clark 2021년 4월 25일
댓글: Brendan Clark 2021년 4월 25일
I'm trying to use nargin to set a default input for a function, should that default not be previously defined by the user. I'm setting up the nargin loop in the same format my teacher used, however, I'm getting an error saying N is undefined, which is technically the point. Irronically I ran my teachers function and it also had the same error... so I'm a little stuck at the moment.
This is my function at the moment.
function y = estimate_pi_Leibniz_Clark_Brendan(N)
if (nargin == 0)
N = 10;
end
p = 0 ;
for k = 0:N
p = p + 4*((-1)^(k)*(1/(2*k+1)));
end
y=p;
  댓글 수: 2
Jonas
Jonas 2021년 4월 25일
looks good, how did you run your function?
Brendan Clark
Brendan Clark 2021년 4월 25일
편집: Brendan Clark 2021년 4월 25일
I just attempted to run in by entering
y = estimate_pi_Leibniz_Clark_Brendan(N)
into the command window, when I preset N the function works exactly how its supposed to, it only kicks back an error when I attempt to run it without predetermining N.

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

채택된 답변

the cyclist
the cyclist 2021년 4월 25일
편집: the cyclist 2021년 4월 25일
When you tried to call it like this:
y = estimate_pi_Leibniz_Clark_Brendan(N)
the problem is that in the calling workspace, the variable N does not exist, which is why you get that error. (The error is from the calling workspace, not from your function.)
Instead you could have called it as
y = estimate_pi_Leibniz_Clark_Brendan()
which would trigger your nargin statement.
  댓글 수: 1
Brendan Clark
Brendan Clark 2021년 4월 25일
I appreciate the explanation, knowing about why those weird errors populate really helps me moving forward.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Simulink Environment Customization에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by