Use vector input to anonymous function and append output to a vector (to plot the results).

I have written a short code to calculate the forward difference and relative error of a function at a point with a variable step size "h". I can succesfully calculate the forward difference at a single step size and have created a vector of values of "h" . When I try to use the vector of step sizes in my equation for the forward difference it only calculates the difference using the first value in the step size vector. I don'y understand why.
My intent is to calculate the value of the forward difference for all values of "h" and append the results to a single vector so that I can plot them on a graph with relative error. I will need to use the same approach to make a relative error plot. Here is my code:
% clear the command window, workspace, and any plots to avoid error in future calcs.
clc
clear
clf
% declare symbolic variables
syms x1 x2 h
% Declare the function
F = (x1+10).^2 + (x2+5).^2 + exp(-(x1.^2)-(x2.^2));
% find the symbolic gradient
g = gradient(F,[x1,x2]);
V = double(subs(g,{x1,x2},{-8,-8}));
grad_f = sum(V);
% set point of interest
x1=-8;
x2=-8;
% setup given function
A = @(x1,x2) (((x1)+10).^2) + (((x2)+5).^2) + exp(-(((x1).^2)-((x2).^2)));
F = A(x1,x2);
a = [1:1:25];
h = [10.^(-a)];
FWD = [(A(x1+h,x2+h) - F)/h]

 采纳的回答

Use "./" rather than "/" in your calculation of FWD, in order to do element-wise division.
% clear the command window, workspace, and any plots to avoid error in future calcs.
clc
clear
clf
% declare symbolic variables
syms x1 x2 h
% Declare the function
F = (x1+10).^2 + (x2+5).^2 + exp(-(x1.^2)-(x2.^2));
% find the symbolic gradient
g = gradient(F,[x1,x2]);
V = double(subs(g,{x1,x2},{-8,-8}));
grad_f = sum(V);
% set point of interest
x1=-8;
x2=-8;
% setup given function
A = @(x1,x2) (((x1)+10).^2) + (((x2)+5).^2) + exp(-(((x1).^2)-((x2).^2)));
F = A(x1,x2);
a = [1:1:25];
h = [10.^(-a)];
FWD = [(A(x1+h,x2+h) - F)./h]
FWD = 1×25
-1.8000 -1.9800 -1.9980 -1.9998 -2.0000 -2.0000 -2.0000 -2.0000 -2.0000 -2.0000 -2.0000 -2.0002 -2.0073 -1.9540 -1.7764 0 0 0 0 0 0 0 0 0 0

更多回答(1 个)

类别

帮助中心File Exchange 中查找有关 Time Series Objects 的更多信息

产品

版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by