Luchspeter
Luchspeter

Reputation: 804

Matlab function - How to get a "clear" function

I have a very long equation (Taylor polynomial) with coefficients fa, fxa, fya (and so on, see below). These are for approximating the value of the function f at the point A = (a,b). The variables a and b are the two components of the point I want to develop the Taylor polynomial around.

The equation:

t = @(x,y) fa + fxa .* (x-a) + fya .* (y-b) + 1/2 .* fxxa.*(x-a).^2 + ...
           1/2 .* fxya .* (x-a).*(y-b) + fyya .* (y-b).^2 + ...
           1/6 .* fxxxa .* (x-a).^3 + 1/2 .* fxxya .* (x-a).^2.*(y-b) + ...
           1/2 .* fxyya .* (x-a).*(y-b).^2 + 1/6 .* fyyya .* (y-b).^3;

All of the variables named like fxyya, are integer values.

I want to have a version of the fuction t, where my calculated coefficients are acutally "put in" and not only the variable names like fxxy and fxya.

For instance, all 0 terms disappear and so on.

Ho do I get that?


For reference, all of the code:

    syms x y;
%f = input('Bitte geben Sie die zu evaluierende Funktion ein:','s');
f = 'exp(x^2+y^3)+x*y*(x+y)';
f = sym(f);
f = symfun(f, symvar(f, 2));
a = 0;
b = 0;

fx = diff(f,x);
fy = diff(f,y);
fxx = diff(fx,x);
fyy = diff(fy,y);
fxy = diff(fx,y);
fxxx = diff(fxx,x);
fxxy = diff(fxx,y);
fxyy = diff(fxy,y);
fyyy = diff(fyy,y);

fa = f(a,b);
fxa = fx(a,b);
fya = fy(a,b);
fxxa = fxx(a,b);
fyya = fyy(a,b);
fxya = fxy(a,b);
fxxxa = fxxx(a,b);
fxxya = fxxy(a,b);
fxyya = fxyy(a,b);
fyyya = fyyy(a,b);
 t = @(x,y) fa + fxa .* (x-a) + fya .* (y-b) + 1/2 .* fxxa.*(x-a).^2 + 1/2 .* fxya .* (x-a).*(y-b) + fyya .* (y-b).^2 + 1/6 .* fxxxa .* (x-a).^3 + 1/2 .* fxxya .* (x-a).^2.*(y-b) + 1/2 .* fxyya .* (x-a).*(y-b).^2 + 1/6 .* fyyya .* (y-b).^3;

Upvotes: 1

Views: 76

Answers (1)

Wolfie
Wolfie

Reputation: 30175

You can just use subs(t), but below is a cleaner version of your code without the need for subs...


You state that the coefficients are integers, but your example code creates them as analytically differentiated syms variables! Here is an adaptation of your code, which doesn't require subs to be used.

% Set up symbolic x and y, and symbolic function f
syms x y;
f = symfun(exp(x^2+y^3)+x*y*(x+y), [x y]);
% Set up points a and b
a = 0; b = 0;
% Get derivative functions analytically (these need to be evaluated at some points x,y)
fx = diff(f,x);     fy = diff(f,y);
fxx = diff(fx,x);   fyy = diff(fy,y);    fxy = diff(fx,y);   
fxxx = diff(fxx,x); fxxy = diff(fxx,y);  fxyy = diff(fxy,y);
fyyy = diff(fyy,y);
% Define symbolic function t
t = symfun(f(a,b) + fx(a,b).*(x-a) + fy(a,b).*(y-b) + ...
    (1/2).*fxx(a,b).*(x-a).^2 + (1/2).*fxy(a,b).*(x-a).*(y-b) + fyy(a,b).*(y-b).^2 + ...
    (1/6).*fxxx(a,b).*(x-a).^3 + (1/2).*fxxy(a,b).*(y-b).*(x-a).^2 + ...
    (1/2).*fxyy(a,b).*(x-a).*(y-b).^2 + (1/6).*fyyy(a,b).*(y-b).^3, [x,y]);

t
% output: t(x, y) = x^2*y + x^2 + x*y^2 + y^3 + 1

Upvotes: 1

Related Questions