具有保持功能的多函数图 [英] Multiple function plots with hold on

查看:47
本文介绍了具有保持功能的多函数图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下代码,我可以通过 hold on 命令绘制两个图.

With the following code, I am able to draw two plots via the hold on command.

x=0:0.1:10;
r1 = 1;
y1=r1 * x .^ 2;
plot( x, y1 );
hold on;
r2 = 1.5;
y2=r2 * x .^ 2;
plot( x, y2 );

但是,我正在寻找一种方法来定义 r=1:0.5:2 并在一个图中绘制三个图表.像这样

However, I am looking for a way to define r=1:0.5:2 and plot three diagrams in one plot. Something like this

x=0:0.1:10;
r=1:0.5:2;
y=r * x .^ 2;
plot( x, y );
hold on;

但由于矩阵乘法,它不正确.

But it is not correct due to the matrix multiplications.

问题与内部矩阵维度有关,例如此处.但我的好像不一样.

The problem is related to inner matrix dimensions, e.g here. But mine seems to be different.

推荐答案

你们已经很接近了.有两种方法可以做你想做的事.第一种方法是使用循环并遍历 r 的每个参数并绘制您的点.第二种方法(对我来说更优雅)是创建一个点矩阵并同时绘制所有点 - r 的每个值一个图.让我们从第一种方法开始:

You're very close. There are two ways to do what you want. The first way is to use a loop and loop over each parameter of r and plot your points. The second way (which is more elegant to me) is to create a matrix of points and plot all of those simultaneously - one plot for each value of r. Let's start with the first approach:

简单地遍历 r 的每个值并绘制它:

Simply iterate over each value of r and plot it:

x=0:0.1:10;
for r = 1:0.5:2 % Change
    y=r * x .^ 2;
    plot( x, y );
    hold on;
end

如您所见,您需要进行的唯一更改是将 r 语句更改为 for 循环.这样,我们将在同一张图上自动用三种不同的颜色绘制三个图.

As you can see, the only change you need to make is to change the r statement into a for loop. This way, we will plot three graphs on the same plot with three different colours automatically.

一种相当优雅的方法是执行乘法和广播.具体来说,将 x 的每个元素平方,转置它然后使用 bsxfun 结合 times 函数执行逐元素乘法,这样您就可以创建一个三列矩阵 - 每列定义 xr 的每个值进行评估.您可以通过一个 plot 调用同时绘制在这个点矩阵中定义的所有图形.

A way to do this rather elegantly is to perform multiplication and broadcasting. Specifically, square each element of x, transpose it then use bsxfun combined with the times function to perform element-wise multiplication so that you can create a matrix of three columns - each column defines the points of x evaluated for each value of r. You can plot all graphs simultaneously defined within this matrix of points with one plot call.

换句话说:

x = 0:0.1:10;
r = 1:0.5:2;
y = bsxfun(@times, r, (x.^2).');
plot(x, y);

在 MATLAB R2016b 及更高版本中,您可以本机执行此乘法并在内部进行广播:

In MATLAB R2016b and up, you can perform this multiplication natively and it will broadcast internally:

x = 0:0.1:10;
r = 1:0.5:2;
y = r * (x.^2).';
plot(x, y); 

这篇关于具有保持功能的多函数图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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