2

我无法打印出 h_a_b。我能够得到函数 f 和 g 但不是这个。我需要使用 h_a_b 函数,所以我可以做 h(f(x),g(x)) 并计算 h(a,b) 的 sqrt。见方程

我总是收到这个错误

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

我想编写一个程序来创建代表函数的 3 个匿名函数

需要的方程

f(x) = 10*cos x ,

g(x) = 5*sin * x,并且

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

这是我的代码

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

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

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

然后我用给我的这个函数来绘制它。

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 
4

1 回答 1

4

因为您的函数 ( h_a_b) 将向量作为输入并给出标量作为输出,所以它表示一个表面,因此plot不能用于可视化它(仅适用于 2D 标量标量图)。

你在寻找这样的东西吗?:

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')

在此处输入图像描述 在此处输入图像描述


第二个选项,考虑z作为标量标量函数并使用您的plotfunc函数:

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)

在此处输入图像描述

这是上面表面的一片。

于 2014-11-14T07:05:46.003 回答