mahmood
mahmood

Reputation: 24685

Multiple function plots with 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 );

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.

Upvotes: 1

Views: 299

Answers (1)

rayryeng
rayryeng

Reputation: 104464

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:

Using a loop

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

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.

Creating a matrix of points

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.

In other words:

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

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); 

Upvotes: 4

Related Questions