Creating a Nested Function
古いコメントを表示
I am trying to create a nested function, but I get an error saying that the variable that I've chosen is already being used even though that's the variable that I need as an input for my second function to compute the equation.
function [root,numit,err] = newton(x,tol,fx,ddx)
err = abs(fx(x));
numit = 0;
while(err > tol && numit < 1000);
numit = numit + 1;
x = x - fx(x)/ddx(x);
err = abs(fx(x));
end
if (numit == 1000)
disp('Maxed out on iterations.')
err;
end
root = x;
function root = x
dx = 0.001;
for i = 2:length(x)-1;
fx = exp(cos(x) + sin(x)) - 2;
dxf=(diff(2:i)-diff(1:(i-1)))/2*dx';
end
root = dxf(x);
end
end
root is my desired output and it is denoted by x. I keep getting an error about x being used as a variable and in the nested function in the same scope. What am I doing wrong?
回答 (1 件)
Azzi Abdelmalek
2013 年 3 月 29 日
編集済み: Azzi Abdelmalek
2013 年 3 月 29 日
Change the name of your nested function, because you are using x as function name and variable
function root = new_name(x)
7 件のコメント
Kelly
2013 年 3 月 29 日
Azzi Abdelmalek
2013 年 3 月 29 日
編集済み: Azzi Abdelmalek
2013 年 3 月 29 日
whos displays variables in base workspace, the variables inside any function are not displayed. each function has its own workspace
Azzi Abdelmalek
2013 年 3 月 29 日
Also, if the first function is working and you are not getting errors, means the second function is also working
Kelly
2013 年 3 月 29 日
Azzi Abdelmalek
2013 年 3 月 29 日
編集済み: Azzi Abdelmalek
2013 年 3 月 29 日
You do not need to call the nested function, it's called by the main function. If your main function is correct, provide the values of x,tol,fx,ddx then call your function
[root,numit,err] = newton(x,tol,fx,ddx)
Kelly
2013 年 3 月 29 日
編集済み: Azzi Abdelmalek
2013 年 3 月 29 日
Azzi Abdelmalek
2013 年 3 月 29 日
If the answer helped, accept the answer and post a new question.
カテゴリ
ヘルプ センター および File Exchange で Graphics Performance についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!