Creating a Nested Function

조회 수: 11 (최근 30일)
Kelly
Kelly 2013년 3월 29일
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
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
Kelly 2013년 3월 29일
편집: Azzi Abdelmalek 2013년 3월 29일
Ok, I got all the computations to work correctly. Now I'm stuck on plotting. I'm creating a 1x2 and the first plot is just the exact derivative of the function and the second should be the numerical approximation.
clc; clear all; close all;
% Equation 1
tol = 0.001; % for central difference dx == tol
ns = 5;
a = 0;
b = 7;
fx = inline('exp(cos(x) + sin(x)) - 2');
ddx = inline('(exp(cos(x) + sin(x)))*(cos(x)-sin(x))');
% Incremental Search Method
[nroots,low,high] = increm_mod(fx,a,b,ns,tol);
for j = 1:length(low)
fprintf('\n')
disp(['The First Equation has ',num2str(nroots),' roots.'])
fprintf('\n')
fprintf('-----------------------------------------------------------------')
fprintf('\n')
disp('USING THE NEWTON-RAPHSON METHOD:')
fprintf('\n')
% Newton Estimate
guess = 2*(a + b)/3;
[root_n(j),numit_n,err_n(j)] = newton(low(j),tol,fx,ddx);
disp(['Root # ',num2str(j),' = ',num2str(root_n(j))])
disp(['Error # ',num2str(j),' = ',num2str(err_n(j))])
disp(['Number of Iterations # ',num2str(j),' = ',num2str(numit_n)])
fprintf('\n')
end
n = 0;
ns = 100;
dx = (b-a)/ns;
for j = a:dx:b
n = n+1;
f_p(n) = fx(j);
x_p(n) = j;
end
figure(1)
subplot(2,1,1)
plot(x_p,f_p);
hold on
grid on
plot(fx,dx,'ko')%%%%%%%%here's is my problem
xlabel('x-values')
ylabel('fx')
title('Solution Using Newton-Raphson')
subplot(2,1,2)
plot(root_n,root_err,'ko')
xlabel('x values')
ylabel('my function')
I'm not sure if I'm plotting the right variables for the derivative because my function and derivative are inline functions.
Azzi Abdelmalek
Azzi Abdelmalek 2013년 3월 29일
If the answer helped, accept the answer and post a new question.

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by