Removing a syms variable from a For loop solution

6 views (last 30 days)
Hello there, I am trying to create a for loop function for a simple formula that includes differentiationCapture.JPG but I am getting the solution :
ans =
[ x, -2510341221049253/4503599627370496, 296951380318845/4503599627370496, -3448745601629/36028797018963968, 21572111/73786976294838206464, 0, 0]
which is correct but is there a way to remove the x? Here is my code. Any help is greatly appreciated!
function x = newton3(Func, x1, N)
syms x
F(x) = diff(Func(x));
%apply Newton's Method
a=Func(x1);
b=double(F(x1));
d = x1 - (a/b);
%apply Newton's Method
%ans=[;];
for i=1:N
syms x;
F(x) = diff(Func(x));
a=Func(x1);
b=double(F(x1));
c=a/b;
d(i) = x1 - c;
x=[x,d];
x1=d(i);
%ans=[ans;x1];
%iterate through Newton's method N times and store results in vector
end

Answers (1)

Agnish Dutta
Agnish Dutta on 20 Mar 2019
Based on on the provided equation and code, here's something I came up with to calculate the neede values:
syms x
N = 100 % No. of itereations.
% I've taken a sample function to demonstrate. Simply replace the RHS of f(x) with your desired function.
f(x) = 5*x^2 - 3*x + 7;
f_prime(x) = diff(f(x));
x_init = f(0) / f_prime(0);
% An array to hold intermediate and the final values.
vals = [];
vals(1) = x_init;
% Loop to calculate the values in each iteration.
for i = 2:N
vals(i) = vals(i - 1) + f(i) / f_prime(i);
end
If however, you wish to keep the rest of your code intact and just remove the first element from the array that stores your result:
ans = ans(2: end)

Categories

Find more on Symbolic Math Toolbox in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!