问题
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