I am struggling to store a function without it being evaluated so the function can be differentiated later.

4 views (last 30 days)
This is my code:
function res = tayexp(x,a,n)
if x <= 0
error ("x is not within the domain")
elseif isinteger(n) == 0 && sign(n) <= 0
error ("n must be a positive integer")
elseif sign(a) <= 0
error ("a cannot be less than or equal to zero")
else
fd=[];
f2 = [];
startfunc(t) = 1./t + log(t)
for i = (0:1:n-1)
newfunc = diff(startfunc(), i+1);
fd = [fd, subs(newfunc,t,x)];
f2 = [f2, (fd(i+1)*(a)*((x-a)^i)) / factorial(i)];
end
res = sum(f2, "all");
end
%goal: make an array of each derivative to the nth degree for 1/x + log(x)
%from there, evaluate each element at x to make an array of numbers
%then plug each value into the taylor series
My issue is that startfunc insists on being evaluated, leading to an error with t which is just an independent variable without a given value.
I have tried nested functions, i have tried making t an empty array, i have tried the @(t) syntax, and none of it seems to work. Any help would be greatly appreciated.

Answers (1)

Steven Lord
Steven Lord on 23 Oct 2024
The correct syntax to make that into an anonymous function is:
startfunc = @(t) 1./t + log(t)
startfunc = function_handle with value:
@(t)1./t+log(t)
Then evaluating it works like:
y = startfunc(1:5)
y = 1×5
1.0000 1.1931 1.4319 1.6363 1.8094
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
  2 Comments
Jaden
Jaden on 24 Oct 2024
Hello! Using your suggestions, a lot of googling, and some ai, I managed to get the code to run! Thanks for the help, hopefully I won't need more help with additions to this code.

Sign in to comment.

Products


Release

R2024b

Community Treasure Hunt

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

Start Hunting!