View Raw SPL
/*****************************************************************************
*                                                                            *
*   GRADIENT.SPL Copyright (C) 1998 DSP Development Corporation              *
*                               All Rights Reserved                          *
*                                                                            *
*   Author:      Randy Race                                                  *
*                                                                            *
*   Synopsis:    Performs 2D derivative of an array                          *
*                                                                            *
*   Revisions:   25 Mar 1998  RRR  Creation                                  *
*                                                                            *
*****************************************************************************/

#include 

#if @HELP_GRADIENT

    GRADIENT

    Purpose: Calculates the 2D derivative of an array

    Syntax:  GRADIENT(array)

              array - a multi-column series

    Returns: An array

    Example:
             (x, y) = fxyvals(-2, 2, .1, -2, 2, .1);
             z = cos(x*y);
             g = gradient(z);

             Calculates the surface derivative of cos(x*y).

             W1: plot3d(g)
             W2: plot3d(z);shadewith(w1);

             Shades the original surface with it's gradient.


    Remarks:
             If the input is a series, the derivative is returned.


    See Also
             DERIV

#endif


gradient(a)
{
        local fx, fy;

        if (not(isarray(a)))
        {
                error(sprintf("%s - series or array expected", __FUNC__));
        }

        if (numcols(a) == 1 || isxy(a))
        {
                return(deriv(a));
        }
        else
        {
                fx = deriv(a);
                fy = transpose(deriv(transpose(a)));

                if (outargc > 1)
                {
                        return(fx, fy);
                }
                else
                {
                        return(sqrt(fx^2 + fy^2));
                }
        }
}