Search code examples
matlabdistancesymbolic-mathnormabsolute-value

Absolute values in Matlab symbolic expressions


In a paper I'm reading, they write

|x-y|^2

I'm trying to code this in Matlab using symbolic tools and I'm not quite sure how to read this, but I want to be sure to capture the proper interpretation. They don't really specify in the paper, but from what I read here, it would be proper to call it a norm versus absolute value. Anyway, it seems as though Matlab does not like me writing

(norm(x-y))^2

using symbolic variables. If I read the equation as absolute value squared,then I can simply dump the need for norm and write

(x-y)^2

I know it sounds trivial, but I'm finding that Matlab does not like the inclusion of the norm (or absolute value) in symbolic expressions. I've put some code below. My question is....is there a proper way to use norm with symbolic variables? If I was dealing with an norm3 (for argument sake), and needed to use it in symbolic expressions, how would I modify the code to still be able to plot?

clear all
clc
syms x lim A real
expression = 2*A*cos(x);

% Squaring
metric = (x - expression)^2;
sq_ = eval(subs(metric,{'x','A'},{linspace(-1,1,10),1}));
error = -int(metric,x,0,lim);
ezsurf(error,[0,pi,-1,2])
view(127,38)

% Using norm
metric = (norm(x - expression))^2;
norm_ = eval(subs(metric,{'x','A'},{linspace(-1,1,10),1}));
error = -int(metric,x,0,lim);
ezsurf(error,[0,pi,-1,2])
view(127,38)

% Using abs
metric = (abs(x - expression))^2;
abs_ = eval(subs(metric,{'x','A'},{linspace(-1,1,10),1}));
error = -int(metric,x,0,lim);
ezsurf(error,[0,pi,-1,2])
view(127,38)

sq_==norm_
sq_==abs_

Solution

  • I am not sure why the symbolic toolbox fails here, especially because it can solve int(metric,x) in any of the cases.

    Replace your single line with two lines and you get the result:

    clear all
    clc
    syms x lim A real
    expression = 2*A*cos(x);
    
    % Squaring
    metric = (x - expression)^2;
    sq_ = eval(subs(metric,{'x','A'},{linspace(-1,1,10),1}));
    error = -int(metric,x,0,lim);
    ezsurf(error,[0,pi,-1,2])
    view(127,38)
    
    % Using norm
    metric = (norm(x - expression))^2;
    norm_ = eval(subs(metric,{'x','A'},{linspace(-1,1,10),1}));
    %error = -int(metric,x,0,lim);
    e2=-int(metric,x);
    error=subs(e2,x,lim)-subs(e2,x,0);
    ezsurf(error,[0,pi,-1,2])
    view(127,38)
    
    % Using abs
    metric = (abs(x - expression))^2;
    abs_ = eval(subs(metric,{'x','A'},{linspace(-1,1,10),1}));
    %error = -int(metric,x,0,lim);
    e2=-int(metric,x);
    error=subs(e2,x,lim)-subs(e2,x,0);
    ezsurf(error,[0,pi,-1,2])
    view(127,38)