Matlab: Plot multiple anonymous functions using fplot

▼魔方 西西 提交于 2019-12-11 02:39:49

问题


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?


回答1:


If you really must do this:

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

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.

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.


来源:https://stackoverflow.com/questions/18648914/matlab-plot-multiple-anonymous-functions-using-fplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!