Matlab:使用fplot绘制多个匿名函数 [英] Matlab: Plot multiple anonymous functions using fplot

查看:2111
本文介绍了Matlab:使用fplot绘制多个匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试创建两个匿名函数,并使用单个 fplot 语句绘制它们。以下代码可用于绘制单个函数:

I am trying to create two anonymous functions and plot them using a single fplot statement. The following code works to plot a single function:

f = @(x) sin(x)

fplot(f, [-3, 3])

然而,当我包含以下内容时,它不起作用:

However, when I include the following, it doesn't work:

g = @(x) cos(x)

fplot([f, g], [-3, 3])

有谁知道这里有什么问题?

Does anyone know what is the issue here?

推荐答案

如果您确实需要这样做:

If you really must do this:

>> f = @sin;
>> g = @cos;
>> hold on
>> cellfun(@(func) fplot(func, [-3, 3]), {f, g})

这将函数句柄应用于单元数组 @(func)fplot(func,[-3,3]) > {f,g} 。既然我也叫按住,这两个函数都会显示在结果图中。如果你没有把保存在上,你会看到 cos(x),因为这是最后一个函数被绘制出来。

This applies the function handle @(func) fplot(func, [-3, 3]) to each of the elements in the cell array {f, g}. Since I also called hold on, both functions will show up in the resulting plot. If you don't call hold on, you'll just see cos(x) since that's the last function that was plotted.

你不能在标准MATLAB数组中保存函数句柄。你应该使用单元阵列。

You cannot hold function handles in standard MATLAB arrays. You should use cell arrays for that.

如果你阅读错误信息,试图将一个函数句柄放入一个标准数组中,你会得到一个关于什么的信息做:

If you read the error message you get from trying to put a function handle into a standard array you get an informative message about what to do:

>> [f, g]
Error using horzcat
Nonscalar arrays of function handles are not allowed; use cell arrays instead.

这篇关于Matlab:使用fplot绘制多个匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆