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

20 次查看(过去 30 天)
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.

回答(1 个)

Steven Lord
Steven Lord 2024-10-23,4:36
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 个评论
Jaden
Jaden 2024-10-24,2:14
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Time Series Events 的更多信息

产品


版本

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by