matlab绘制一系列函数

matlab plotting a family of functions

生成图表显示

y=(2*a+1)*exp(-x)-(a+1)*exp(2*x)

在 x ∈ <-2, 4> 范围内,对于 a 在 -3 和 3 之间的所有整数值

我知道如何绘制 2 个值的典型图并在轴上设置范围,但如何根据参数 a 绘制图形?

您可以使用一个简单的 for 循环,如下所示。您基本上遍历 a 的每个值并绘制相应的 y 函数。

clear
clc
close all

x = -2:4;

%// Define a
a = -3:3;

%// Counter for legend
p = 1;
LegendText = cell(1,numel(a));

figure;
hold on %// Important to keep all the lines on the same plot.

for k = a

    CurrColor = rand(1,3);

    y= (2*k+1).*exp(-x)-(k+1).*exp(2.*x);

    plot(x,y,'Color',CurrColor);

    %// Text for legend
    LegendText{p} = sprintf('a equals %d',k);
    p = p+1;
end
legend(LegendText,'Location','best')

这给出了这样的东西:

您可以根据需要自定义图表。希望对您有所帮助!

详细说明 :一种更高级的技术是用调用 bsxfun 来替换 for 循环,以生成 [=14= 的评估矩阵] 并使用此矩阵调用 plot。然后 Matlab 将使用矩阵的列并用单独的颜色绘制每一列。

%%// Create a function handle of your function
f = @(x,a) (2*a+1)*exp(-x)-(a+1)*exp(2*x);
%%// Plot the data
x = linspace(-2, 4);
as = -3:3;
plot(x, bsxfun(f,x(:),as));
%%// Add a legend
legendTexts = arrayfun(@(a) sprintf('a == %d', a), as, 'uni', 0);
legend(legendTexts, 'Location', 'best');

您还可以使用 ndgrid 创建评估矩阵,它明确 returns xas 值的所有组合。在这里,您必须更加注意正确矢量化代码。 (我们很幸运,bsxfun 方法无需更改原始 f。)

f = @(x,a) (2*a+1).*exp(-x)-(a+1).*exp(2*x); %// Note the added dots.
[X,As] = ndgrid(x,as);
plot(x, f(X,As))

但是对于初学者来说,您应该熟悉循环。