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

1 回表示 (過去 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 日
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 件のコメント
Walter Roberson
Walter Roberson 2024 年 10 月 23 日
newfunc = diff(startfunc(), i+1);
will need to be changed to
syms t
newfunc = diff(startfunc(t), i+1);
Jaden
Jaden 2024 年 10 月 24 日
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 Center および File ExchangeTime Series Events についてさらに検索

製品


リリース

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by