Search code examples
matlabanonymous-functionfunction-handle

Trouble with anonymous functions in matlab


I am having trouble with printing out h_a_b. I am able to get functions f and g but not this one. I need to use h_a_b function so i can do h(f(x),g(x)) and calculate the sqrt of h(a,b). see equations

I am always getting this error

Undefined function 'h_a_b' for input arguments of type 'function_handle'.

I am suppose to write a program that create 3 anonymous functions representing the function

Equations needed

f(x) = 10*cos x ,

g(x) = 5*sin * x, and

h(a,b) = \sqrt(a^2 + b^2).

Here is my code

f = @ (x) 5*sin(x); 

g = @ (x) 10*cos(x); 

h_a_b = @ (a,b) sqrt(a.^2 + b.^2);

then I plot it with this function that was given to me.

function plotfunc(fun,points)
%PLOTFUNC Plots a function between the specified points.
% Function PLOTFUNC accepts a function handle, and
% plots the function at the points specified.
% Define variables:
% fun -- Function handle
% msg -- Error message
%

msg = nargchk(2,2,nargin);
error(msg);
% Get function name
fname = func2str(fun);
% Plot the data and label the plot
plot(points,fun(points));
title(['\bfPlot of ' fname '(x) vs x']);
xlabel('\bfx');
ylabel(['\bf' fname '(x)']);
grid on;

end 

Solution

  • Because your function (h_a_b) takes a vector as input and gives scalar as output it represents a surface, thus plot cannot be used to visualize it (that is only for 2D, scalar-scalar plots).

    Are you looking for something like this?:

    f       = @ (x) 5*sin(x); 
    g       = @ (x) 10*cos(x); 
    h_a_b   = @ (a,b) sqrt(a.^2 + b.^2);
    
    z       = @(a,b) sqrt(h_a_b(f(a),g(b)));
    
    [A, B]  = meshgrid(0:0.1:8, 0:0.1:9);
    Z       = z(A,B);
    
    surfc(A,B,Z)
    xlabel('a')
    ylabel('b')
    figure
    contourf(A,B,Z)
    xlabel('a')
    ylabel('b')
    

    enter image description here enter image description here


    Second option, considering z as scalar-scalar function and using your plotfunc function:

    f       = @ (x) 5*sin(x); 
    g       = @ (x) 10*cos(x); 
    h_a_b   = @ (a,b) sqrt(a.^2 + b.^2);
    
    z       = @(x) sqrt(h_a_b(f(x),g(x)));
    
    points = 0:0.1:8;
    plotfunc(z,points)
    

    enter image description here

    Which is one slice of the above surface.