Evaluate function handle with "for"
3 views (last 30 days)
Show older comments
Cynthia Lilian
on 23 Aug 2022
Answered: Walter Roberson
on 23 Aug 2022
I want to write a code to obtain the partial derivates of a function R^n ->R given by the user. For that, the parameters in which I evaluate the function change according to the variable that is being derivated.
I thought about using a FOR loop, but I don't know how to write the code so it will chance the values where the function is evaluated according to the variable.
For example, the code for the first two varibles would be
parcial_1 = (feval(f,x0+h,y0)-feval(f,x0-h,y0))/(2*h);
parcial_2 = (feval(f,x0,y0+h)-feval(f,x0,y0-h))/(2*h);
The full code I have is this
x0 = 2;
y0=2;
h = 0.01;
f=input('Input the function: ');
num_variables=nargin(f);
disp(num_variables);
for i=1:num_variables
parcial_i=(feval(f,x0+h,y0)-feval(f,x0-h,y0))/(2*h);
end
0 Comments
Accepted Answer
Walter Roberson
on 23 Aug 2022
f=input('Input the function: ');
num_variables=nargin(f);
varvals = {2, 2, zeros(1, num_variables-2)};
for i = 1 : num_variables
t1 = varvals; t2 = varvals;
t1{i} = t1{i} + h; t2{i} = t2{i} - h;
partial{i} = (feval(f, t1{:}) - evalf(f, t2{:}))/(2*h);
end
0 Comments
More Answers (0)
See Also
Categories
Find more on Legend 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!