lettura simple

Creating Stair Step Graphs in Matlab

Let's have some fun with Matlab today and dive into the world of stair step graphs!

So, what's the deal with these stair step graphs? Imagine a function's graph, but instead of being smooth and continuous, it looks like a series of stair steps. They're great for showing how a function's values increase or decrease in a more discrete fashion.
Here's a practical example:

Let's start with a simple example.

Suppose we have an array 'x' with values from 1 to 20.

>> x=linspace(1,20,20);

This 'x' array will be the domain of our function.

Next, we'll create an array 'y' for the values of our function y=f(x).

>> y=x

Now, if we type plot(x,y), we'll get the graph of y=f(x).

>> plot(x,y)

What we see is a continuous line from 1 to 20. In our case, it's a straight line passing through the origin.

example of continuous graph

But let's make things more interesting! Type stairs(x,y) to create a stair step graph.

>> stairs(x,y)

With the stairs(x,y) function, we connect adjacent points using a step instead of a continuous line.

The result is a nifty stair step diagram.

Example of cartesian stair step diagram

In this case, the steps are all equal because the linear function has a constant increase at each point.

Now let's kick it up a notch with a more intriguing example.

Let's define a function y=x2 that calculates the square of each value of x.

y=x.^2

Plotting the continuous graph of this function gives us an exponential curve.

the function's graph is an exponential curve

But if we use stairs(x,y) to create the stair step diagram...

>> stairs(x,y)

...we end up with a graph full of steps of varying heights, where the higher steps represent the points where the function grows the most.

example of stair step graph

In this case, the steps tend to increase in height as the value of x increases.

This means that the function grows more than proportionally.

How to display multiple graphs in a single diagram?

Now, you might ask, "What if I want to compare two functions on the same graph?" No problem!

For example, create an array Y with two elements.

Let's use 0.5cos(X) as the first element and 2cos(X) as the second element.

>> X = linspace(0,4*pi,50)';
>> Y = [0.5*cos(X), 2*cos(X)];

Type stairs(Y) or stairs(X,Y) to display both stair step graphs together.

>> stairs(X,Y)

Voila! We have a single Cartesian diagram displaying the stair step graphs of both functions, making it easy to compare their behavior.

two function in a stair step graph

And if you're feeling ambitious, you can even display three or more functions in the same graph! Just define an array with three or more elements and follow the same steps.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin